File Reader and Wrapper Class in Java OverView

Java has basic classes for reading and writing files. In this article (still incomplete – this is just an overview) we’ll discuss the FileReader class and make a simple program to read a specified line from a file. We’ll do this by writing two classes. One will be the primary class of our program where our main method will appear in which we will call the second class which will grab a file and which will contain a method for reading a line. The first class should appear as…

public class FileReader {

public static void main(String[] args) {
System.out.println(new MyFileReader().read_specified_line(4));
}

}

That is pretty basic. We save it in MyFileReader.java and we are good to go. The problem is that the class we referenced (“MyFileReader”) doesn’t exist yet so we need to write it. So create a new file called MyFileReader.java and write the following…

import java.io.*;
import java.io.FileReader;

public class MyFileReader {
BufferedReader input;
MyFileReader(){
File f = new File(“readthisfile.txt”);
try {
input = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String read_next_line(){
try {
return input.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return “Problem reading a single line”;
}

public String read_specified_line(int x){
int number = 1;
while (number < x){ read_next_line(); number = number + 1; } return read_next_line(); } } Now we just have to make sure the file "readthisfile.txt" exists in the proper place within the system so that it can be read (and has at least 4 lines since that's what we are trying to read). Usually this is in the upper folder of the project, but you can specify the full path if needed.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply