How to read a text file in Java
Tuesday, April 15, 2008
Reading files from disk is an important and common task that is required in many programs. We’ll take a look at one way to read text files using Java.
Using the BufferedReader
class
The java.io
package contains many input and output (I/O) classes.
One useful class for reading text files is the java.io.BufferedReader
class.
It is particularly useful because of its BufferedReader.readLine()
method, which allows for reading a line of text from a file.
Another class that will be used is the java.io.FileReader
class, which will read a specified file.
The BufferedReader
will be used as a wrapper to read the file one line at a time.
The following is an example of a program that reads the contents of a text file line-by-line and reads it into a String:
import java.io.*;
/**
* This program demonstrates how to read a text file.
* @author coobird
*/
public class TextReadingApp {
public static void main(String[] args) {
// Will be used later to store the contents of a file.
String contents= "";
try {
// A BufferedReader is instantiated with a newly instantiated
// FileReader as its underlying reader.
BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
// A while-loop will continue to execute until the end of file
// is reached, at which point br.ready() returns false.
while (br.ready()) {
// Concatenates the current line to another string.
// The newline character is added, as the readLine()
// method returns a String without the newline.
contents += br.readLine() + "\n";
}
} catch (FileNotFoundException e) {
// Thrown by FileReader(String)
e.printStackTrace(System.out);
} catch (IOException e) {
// Thrown by br.ready()
e.printStackTrace(System.out);
}
// Displays the contents of the file.
System.out.println(contents);
}
}
In the above program runs as follows:
- A
BufferedReader
wraps around aFileReader
to read a text file called “textfile.txt
”. - Once the file is opened and is ready for reading, the
while
loop runs as long as there is more lines to read from the text file. - The
BufferedReader.ready()
method, which returnstrue
whenBufferedReader
has more lines to read, is used as the loop condition. BufferedReader.readLine()
method return a line from the text file as aString
without the newline and carriage feed.- The returned
String
is concatenated to theString
variablecontents
which is used to store the text being read from the file. (Hence there’s a"\n"
that’s concatenated to the string.) - At the end of the program, it displays the contents of the text file to the console.