O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required