Nov 102012
 
Article Java

The most common way to read a text file in Java is using a BufferedReader as shown below:

In this example, the name of the file to be read is passed as an argument to the “read_file” program.

First, the file is opened in a FileReader. This way we get a low-level input/output handler “fr”.

Next, a BufferedReader object “br” is obtained from the FileReader handler “fr”. The “br” handler takes care of optimizing disk access, reading data in 8KB blocks, and splitting them in lines.

Lines are returned to the main program one at a time with every call to the readLine() method from BufferedReader.

readLine returns null when the end of file is reached.

Finally, the input file is closed with a call to the close() method of the “fr” FileReader (closing in turn the “br” BufferedReader).

As we can see in the sample above, the code that reads the text file has been enclosed in a “try {} catch {}” block, to be able to react to errors/exceptions that could happen while reading the file.

How to read files in non-default character encodings.

The FileReader class used in the previous section is a subclass of InputStreamReader. FileReader assumes that the file being read uses the system default character encoding.

In case we need to read files in a different character encoding (“utf8”, “latin1”,…), we can create an InputStreamReader object, specifying the desired character encoding at the time the object is created. For instance:

As we can see, a FileInputStream is created first, and then an InputStreamReader is created on top of it. Finally, to improve the performance, a BufferedReader is created on top of the InputStreamReader, as in the previous example.

 Posted by at 5:51 pm

 Leave a Reply

(required)

(required)