Java Input/Output  «Prev  Next»

Lesson 9 Working with text files
ObjectiveRead and write text files.

Working with Text Files

The FileReader and FileWriter classes are very useful for reading from and writing to text files.
Following are the two main constructors used to create FileReader and FileWriter objects:

public FileReader(String fileName)
public FileWriter(String fileName)

Stream Objects

Since both of these objects represent streams, you can use them in conjunction with other stream objects. Additionally, they support the familiar read() and write() methods that are so prevalent in Java's stream classes.
The BufferedReader class is commonly used with FileReader since it is more efficient. It provides a readLine() method that is useful for reading entire lines of text at a time.
Following is an example of reading and printing lines of text from a file named Notes.txt:

BufferedReader in = new BufferedReader(new FileReader("Notes.txt"));
String s;
while ((s = in.readLine()) != null)
System.out.println(s);

In this example, the while loop checks to see if the end of the file has been reached, as indicated by the readLine() method returning null. The readLine() method returns each line of text as a string, which is then printed to standard output. Following is a similar example that reads a text file and writes its contents to another text file:


BufferedReader in = new BufferedReader(new FileReader("Notes.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("Copy.txt"));
String s;
while ((s = in.readLine()) != null)
out.write(s, 0, s.length());

Provide 0 as offset

This example writes each line of text to the file named Copy.txt using the write() method. This version of the write() method expects a string, offset, and number of characters as its parameters. By providing 0 as the offset and s.length() as the number of characters, the entire string is written each time through the loop.
Note: It is worth noting that most of the Java I/O class constructors and methods are capable of throwing[1] exceptions, which means that you will typically place I/O code within a try-catch construct.

Data File Reader - Exercise

Click the Exercise link below to read from a file.
Data File Reader - Exercise

[1] Throwing (an exception): When an exceptional condition is encountered in a Java program, an exception is thrown, which means that a special exception object is created and passed out of the current context. The idea is that a higher context will be more capable of handling the exception.