FileWriter Class

Package: java.io

The FileWriter class connects to a File object and provides the basic ability to write to the file.

In most cases, you won’t use methods of this class directly. Instead, you’ll use this class to connect to BufferedWriter, which extends the FileWriter class by providing buffering for more efficient output. Then, you’ll connect the Buffered Writer object to a PrintWriter object, which has more useful methods for writing output data to a character stream. As a result, this section shows only the constructor for the FileWriter class and not its methods. For more information, see PrintWriter Class.

CrossRef.eps The FileWriter class is one of many Java I/O classes that use streams. For more information, see Streams (Overview).

Constructors

Constructor

Description

FileWriter(File file)

Creates a file writer from a File object. Throws IOException if an I/O error occurs.

FileWriter(File file, boolean append)

Creates a file writer from a File object and throws IOException if an I/O error occurs. If the second parameter is true, data is added to the end of the file if the file already exists.

The following example shows how to create a FileWriter object that appends to an existing file:

File f;

FileWriter fwriter;

f = new File(“myfile.txt”);

fwriter = new FileWriter(f, true);

Get Java For Dummies Quick Reference 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.