Reading a file is going to require using a stream like we’ve seen before. The we will read through the file.
Opening the File
First we will need to set up a FileReader object, such as:
// fname is the name of a file to load
FileReader fileReader = new FileReader(fname);
Note, in order to use FileReader, you will need to import java .io into your project.
import java.io.*;
However, we will wrap the FileRead in a BufferedReader like we did when reading from a console.
BufferedReader br = new BufferedReader(fileReader);
Of course, this can be combined as it was in the console example.
BufferedReader br = new BufferedReader( new FileReader(fname) );
The use of anonymous objects is fairly common in Java and this is something that you will likely see. Of course, one big change is we will want to define the object and instantiate it in two different locations, so you can properly use the try/catch blocks.
The completed block to handle opening a file would look something like what you see below.
BufferedReader br = null;
String fname = "data.txt";
try {
br = new BufferedReader(new FileReader(fname));
// do other things...
} catch (IOException ioe) {
// handle the exception appropriately
}
Closing the File
We will close the file in the finally, that way it happens regardless of if there was an error or not.
finally {
try {
br.close();
} catch(IOException ioe) {}
}
Note that closing the buffered reader should automatically close the FileReader object.
Also note that the close method has to be caught, even though it is in the finally clause – this is just in case the buffered reader wasn’t actually opened.
Reading the File
I like to do the opening and closing of the file first, so I don’t forget to so all the parts. Then I like to go in and read the actual file.
There is an easy way to read in the file line by line.
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
The creates a string object, and then assigns it the value of the read line.
The !=null is a great way to check the value of the line, and read it until there is nothing left in the file. Some languages have a method to check for end of file, but you cannot do this with a buffered reader, so this provides a nice alternative.
Now what happens with this line of text is up to you and based upon the context of the application. It may need be converted into a different data type. It might need to be parsed, etc, but there are options for you to consider.
Reading Files with Java was originally found on Access 2 Learn
One Comment
Comments are closed.