I'm using RandomAccessFile to create a database to a text file. Basically I created a normal store using an ArrayList and now i need to output the contents of the store using RandomAccessFile. But I am stuck on how to get the randomAccessFile method to take the student store. Here is my code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
public class MainApp
{
private RandomAccessFile File;
public static void main(String[] args) throws Exception
{
new MainApp().start();
}
public void start()throws Exception
{
StudentStore details = new StudentStore();
Student a = new Student("Becky O'Brien", "DKIT26", "0876126944", "bexo#hotmail.com");
Student b = new Student("Fabio Borini", "DKIT28", "0876136944", "fabioborini#gmail.com");
Student c = new Student("Gaston Ramirez", "DKIT29", "0419834501", "gramirez#webmail.com");
Student d = new Student("Luis Suarez", "DKIT7", "0868989878", "luissuarez#yahoo.com");
Student e = new Student("Andy Carroll", "DKIT9", "0853456788", "carroll123#hotmail.com");
details.add(a);
details.add(b);
details.add(c);
details.add(d);
details.add(e);
details.print();
//Create a file object.
File contactDetailsFile = new File("StudentDetails.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(contactDetailsFile)));
out.println(a);
out.println(b);
out.println(c);
out.println(d);
out.println(e);
out.close();
BufferedReader in = new BufferedReader(
new FileReader(contactDetailsFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
/**
* #param args the command line arguments
*/
public void RandomAccessFile(String filename)
{
RandomAccessFile randomAccessFile = null;
try {
//Declare variables that we're going to write
String line1 = "First line\n";
String line2 = "Second line\n";
//Create RandomAccessFile instance with read / write permissions
randomAccessFile = new RandomAccessFile(filename, "rw");
//Write two lines to the file
randomAccessFile.writeBytes(line1);
randomAccessFile.writeBytes(line2);
//Place the file pointer at the end of the first line
randomAccessFile.seek(line1.length());
//Declare a buffer with the same length as the second line
byte[] buffer = new byte[line2.length()];
//Read data from the file
randomAccessFile.read(buffer);
//Print out the buffer contents
System.out.println(new String(buffer));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (randomAccessFile != null)
randomAccessFile.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
In a word, yes.
You will, however, have to re-do your write-to-file part of this solution again. You must read objects back out the same way you wrote them.
From this example, you can see how each member is written using the RandomAccessFile object.
I would suggest that you make the read method from the example return a new Student object.
Related
I have this written so far, I am just doing a few practice codes from my text book. I cant seem to get this to read the first line in my .txt .
/**
*
*/
import java.util.Scanner; //needed for scanner class
import java.io.*; //needed for File I/O classes
/**
* #author Megan
*
*/
public class Pres {
/**
* #param args
*/
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter name of file: C:/User/Frances/Documents/USPres.txt");
String filename = keyboard.nextLine();
File file = new File("C:/User/Frances/Documents/USPres.txt");
Scanner inputFile = new Scanner(file);
String line = inputFile.nextLine();
System.out.println("The first line in the file is: ");
System.out.println(line);
inputFile.close();
}
}
I believe it has to do with this portion of the code:
String line = inputFile.nextLine();
I am not quite sure what to type into the (), if I should type anything at all. I could be wrong. My textbook isn't to clear about the proper format. If you could help, please and thank you. :)
To read txt file do this:
String line = "";
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(fileName));
while ((line = in.readLine()) != null) {
// do something here
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
It will read all lines in the text but since it's practice go ahead and try to figure out how to read just one line.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Pres {
public static void main(String[] args) throws FileNotFoundException, IOException {
// BufferedReader is best for read line from file or else
BufferedReader Bfr = new BufferedReader(new FileReader("your_filename_or_path.txt"));
// get first line from file
String firstLinetext = Bfr .readLine();
System.out.println(firstLinetext ); // print first line
}
}
I am new to java, but not coding. I am trying to figure out java because it's part of my class this term and I am having a really hard problem grasping the idea of it and implementing things in java.
my problem Is that I am not sure if I am correctly using the arraylist to grab data from the scan of the file and input it into a arraylist to sort and print at a later time. I am just having issues picking up on java any help would be great since I am new to java.
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.*;
public class MissionCount
{
private static ArrayList<String> list = new ArrayList<String>();
// returns an InputStream that gets data from the named file
private static InputStream getFileInputStream(String fileName) throws Exception {
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(fileName));
}
catch (FileNotFoundException e) { // no file with this name exists
inputStream = null;
throw new Exception("unable to open the file -- " + e.getMessage());
}
return inputStream;
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("USage: MissionCount <datafile>");
//System.exit(1);
}
try {
System.out.printf("CS261 - MissionCount - Chad Dreher%n%n");
int crewcount = 0;
int misscount = 0;
InputStream log = getFileInputStream(args[0]);
Scanner sc = new Scanner(log);
sc.useDelimiter(Pattern.compile(",|\n"));
while (sc.hasNext()) {
String crewMember = sc.next();
list.add(crewMember);
String mission = sc.next();
list.add(mission);
}
sc.close();
// Add code to print the report here
}catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
InputStream log = getFileInputStream(args[0]);
Change that line to as follows :-
File log = new File(args[0])
that should work!
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class Exercise4
{
String name = null;
public String nameInitials(String sentence)
{
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(new FileOutputStream("abc.txt."));
outputStream.println(sentence);
}
catch (FileNotFoundException e)
{
System.out.println("File not found.");
System.exit(0);
}
outputStream.close();
Scanner inputStream = null;
try
{
inputStream = new Scanner(new FileInputStream("abc.txt."));
}
catch (FileNotFoundException e)
{
System.out.println("File not found.");
System.exit(0);
}
do
{
String word = inputStream.next();
char initial = word.charAt(0);
name = initial+"."+name;
} while (inputStream.hasNext());
return name;
}
public void main(String[]args)
{
String initials = nameInitials("Bertrand Arthur William Russell");
System.out.println(initials);
}
}
Write a method called nameInitials that takes one String as argument, pertaining to somebody's full name and returns a String of the name's initials. Usage example,
String initials = nameInitials("Bertrand Arthur William Russell");
System.out.println(initials); //should print B.A.W.R.
I try to store the full name to a txt file and read the file. But I don't know why I cannot create the abc.txt file in the folder.
This can fix your error, I tested it
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class Exercise4
{
static String name = null;
public static String nameInitials(String sentence) {
PrintWriter outputStream = null;
try {
outputStream = new PrintWriter(new FileOutputStream("C:\\temp\\abc.txt"));
outputStream.println(sentence);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
outputStream.close();
Scanner inputStream = null;
try {
inputStream = new Scanner(new FileInputStream("C:\\temp\\abc.txt"));
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
do {
String word = inputStream.next();
char initial = word.charAt(0);
name = initial + "." + name;
} while (inputStream.hasNext());
return name;
}
public static void main(String[] args) {
String initials = nameInitials("Bertrand Arthur William Russell");
System.out.println(initials);
}
}
the path of file not should end of .txt. just .txt
Your code is perfect it is creating the file "abc.txt." at the project level If you want to create a file named abc.txt then you must change;
new FileOutputStream("abc.txt.") to new FileOutputStream("abc.txt")
and
new FileInputStream("abc.txt.") to new FileInputStream("abc.txt")
And if you want to create the file in a particular directory then provide the full path of that directory with the file name you want to create.
for ubuntu system;
new FileOutputStream("/home/java/abc.txt")
&
new FileInputStream("/home/java/abc.txt")
and for windows system;
new FileOutputStream("C:/java/abc.txt")
&
new FileInputStream("C:/java/abc.txt")
I am trying to load in a file from my computer with all the words of the dictionary in the file.
When I load the file i put the words into an array of strings.
I then want to eliminate all words that have more than 9 letters in them.
I then want to save the words that are 9 letters or smaller into another separate text file.
When i try to open the new file it only has 9 words in it, yet my print to the screen on eclipse will print the all words of nine or less letters.
Can anyone help!
This is a program that was gave to me as part of the question.
import java.io.*;
public class FileIO{
public String[] load(String file) {
File aFile = new File(file);
StringBuffer contents = new StringBuffer();
BufferedReader input = null;
try {
input = new BufferedReader( new FileReader(aFile) );
String line = null;
int i = 0;
while (( line = input.readLine()) != null){
contents.append(line);
i++;
contents.append(System.getProperty("line.separator"));
}
}
catch (FileNotFoundException ex) {
System.out.println("Can't find the file - are you sure the file is in this location: "+file);
ex.printStackTrace();
}
catch (IOException ex){
System.out.println("Input output exception while processing file");
ex.printStackTrace();
}
finally {
try {
if (input!= null) {
input.close();
}
}
catch (IOException ex) {
System.out.println("Input output exception while processing file");
ex.printStackTrace();
}
}
String[] array = contents.toString().split("\n");
for(String s: array){
s.trim();
}
return array;
}
public void save(String file, String[] array) throws FileNotFoundException, IOException {
File aFile = new File(file);
Writer output = null;
try {
output = new BufferedWriter( new FileWriter(aFile) );
for(int i=0;i<array.length;i++){
output.write( array[i] );
output.write(System.getProperty("line.separator"));
}
}
finally {
if (output != null) output.close();
}
}
}
this is the class i tried to use
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
public class countdown{
public static void main(String args[]){
FileIO reader = new FileIO();
Scanner scan = new Scanner(System.in);
String[] inputs = reader.load("C:/Users/Sony/Documents/dict.csv"); //Reading the File as a String array from a file called dict
String[] input = new String[inputs.length]; //new String array for strings less than 9 letters
for(int i=0;i<inputs.length;i++){
if(inputs[i].length()<=9) { //if string of index i is less than 9
input[i]=inputs[i]; //add it to the new array called input
System.out.println(input[i]); //print line to check
}
}
try{
reader.save("C:/Users/Sony/Documents/dictnew.csv",input);
//this is where i save it to the new file called dictnew.
}catch (Exception e){
System.out.println(e.getClass());
}
}
}
After reading how you want you can split rest logic remains same.
package com.srijan.playground;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FilterLengthWords {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("Sample.txt"));
bw = new BufferedWriter(new FileWriter("Output.txt"));
String tmp = null;
while((tmp=br.readLine())!=null) {
if(tmp.length()<=9) {
bw.write(tmp);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(br!=null) {
br.close();
br=null;
}
if(bw!=null){
bw.close();
bw=null;
}
}
}
}
Thanks
I need to make my program read a file, then take the numbers in the string and sort them into an array. I can get my program to read the file and put it to a string, but that's where I'm stuck. All the numbers are on different lines in the file, but appear as one long number in the string. This is what I have so far:
public static void main(String[] args) {
String ipt1;
Scanner fileInput;
File inFile = new File("input1.dat");
try {
fileInput = new Scanner(inFile);
//Reads file contents
while (fileInput.hasNext()) {
ipt1 = fileInput.next();
System.out.print(ipt1);
}
fileInput.close();
}
catch (FileNotFoundException e) {
System.out.println(e);
}
}
I recommend reading the values in as numeric types using fileInput.nextInt() or whatever type you want them, putting them in an array and using a built in sort like Arrays.sort. Unless I'm missing a more subtle point about the question.
If your task is just to get input from some file and you're sure the file has integers, use an ArrayList.
import java.util.*;
Scanner fileInput;
ArrayList<Double>ipt1 = new ArrayList<Double>();
File inFile = new File("input1.dat");
try {
fileInput = new Scanner(inFile);
//Reads file contents
while (fileInput.hasNext()){
ipt1.add(fileInput.nextDouble()); //Adds the next Double to the ArrayList
System.out.print(ipt1.get(ipt1.size()-1)); //Prints out what you just got.
}
fileInput.close();
}
catch (FileNotFoundException e){
System.out.println(e);
}
//Sorting time
//This uses the built-in Array sorting.
Collections.sort(ipt1);
However, if you DO need to come up with a simple array in the end, but CAN use ArrayLists, you can add the following:
Double actualResult[] = new Double[ipt1.size()]; //Declare array
for(int i = 0; i < ipt1.size(); ++i){
actualResult[i] = ipt1.get(i);
}
Arrays.sort(actualResult[]);
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class SortNumberFromFile {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
try {
System.out.println("Started at " + LocalDateTime.now());
br = new BufferedReader(new FileReader("/folder/fileName.csv"));//Read data from file named /folder/fileName.csv
List<Long> collect = br.lines().mapToLong(a -> Long.parseLong(a)).boxed().collect(Collectors.toList());//Collect all read data in list object
Collections.sort(collect);//Sort the data
writeRecordsToFile(collect, "/folder/fileName.txt");//Write sorted data to file named /folder/fileName.txt
System.out.println("Ended at " + LocalDateTime.now());
}
finally {
br.close();
}
}
public static <T> void writeRecordsToFile(Collection<? extends T> items, String filePath) {
BufferedWriter writer = null;
File file = new File(filePath);
try {
if(!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
writer = new BufferedWriter(new FileWriter(filePath, true));
if(items != null && items.size() > 0) {
for(T eachItem : items) {
if(eachItem != null) {
writer.write(eachItem.toString());
writer.newLine();
}
}
}
} catch (IOException ex) {
}finally {
try {
writer.close();
} catch (IOException e) {
}
}
}
}