Reading and Writing Files

You’ve already learned how to chain an OutputStreamWriter to a FileOutputStream and an InputStreamReader to a FileInputStream. Although this isn’t hard, Java provides two simple utility classes that take care of the details, java.io.FileWriter and java.io.FileReader.

FileWriter

The FileWriter class is a subclass of OutputStreamWriter that writes text files using the platform’s default character encoding and buffer size. If you need to change these values, construct an OutputStreamWriter on a FileOutputStream instead.

public class FileWriter extends OutputStreamWriter

This class has four constructors:

public FileWriter(String fileName) throws IOException
public FileWriter(String fileName, boolean append) throws IOException
public FileWriter(File file) throws IOException
public FileWriter(FileDescriptor fd)

The first constructor opens a file and positions the file pointer at the beginning of the file. Any text in the file is overwritten. For example:

FileWriter fw = new FileWriter("36.html");

The second constructor allows you to specify that new text is appended to the existing contents of the file rather than overwriting them by setting the second argument to true. For example:

FileWriter fw = new FileWriter("36.html", true);

The third and fourth constructors use a File object and a FileDescriptor, respectively, instead of a filename to identify the file to be written to. Any pre-existing contents in a file so opened are overwritten.

No methods other than the constructors ...

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.