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.
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 allow the reading of file a 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:
BufferedReader
wraps around a FileReader
to
read a text file called "textfile.txt
". while
loop runs as long as there is more lines to read from
the text file. BufferedReader.ready()
method, which returns
true
when BufferedReader
has more lines to
read, is used as the loop condition. BufferedReader.readLine()
method return a line from the
text file as a String
without the newline and carriage feed.
String
is concatenated to the
String
variable contents
which is used to store
the text being read from the file. (Hence there's a
"\n"
that's concatenated to the string.)