Java FileWriter

Jakob Jenkov
Last update: 2019-12-04

The Java FileWriter class, java.io.FileWriter, makes it possible to write characters to a file. In that respect the Java FileWriter works much like the FileOutputStream except that a FileOutputStream is byte based, whereas a FileWriter is character based. The FileWriter is intended to write text, in other words. One character may correspond to one or more bytes, depending on the character encoding scheme in use. The Java FileWriter class is a subclass of the Java Writer class, by the way.

FileWriter Example

Here is a simple Java FileWriter example:

Writer fileWriter = new FileWriter("data\\filewriter.txt");

fileWriter.write("data 1");
fileWriter.write("data 2");
fileWriter.write("data 3");

fileWriter.close();

Note: The proper exception handling has been skipped here for the sake of clarity. To learn more about correct exception handling, go to Java IO Exception Handling.

The FileWriter has other constructors too, letting you specify the file to write to in different ways. Look in the official JavaDoc for more detailed info.

Overwriting vs. Appending the File

When you create a Java FileWriter you can decide if you want to overwrite any existing file with the same name, or if you want to append to any existing file. You decide that by choosing what FileWriter constructor you use.

The FileWriter constructor taking just one parameter, the file name, will overwrite any existing file:

Writer fileWriter = new FileWriter("c:\\data\\output.txt");

FileWriter has a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append or overwrite an existing file. Here are two Java FileWriter examples showing that:

Writer fileWriter = new FileWriter("c:\\data\\output.txt", true);  //appends to file

Writer fileWriter = new FileWriter("c:\\data\\output.txt", false); //overwrites file

FileWriter Character Encoding

The FileWriter assumes that you want to encode the bytes to the file using the default character encoding for the computer your application is running on. This may not always be what you want, and you cannot change it!

If you want to specify a different character encoding scheme, don't use a FileWriter. Use an OutputStreamWriter on a FileOutputStream instead. The OutputStreamWriter lets you specify the character encoding scheme to use when writing bytes to the underlying file.

write(int)

The Java FileWriter write(int) method writes the lower 16 bit of the int to the destination the FileWriter is connected to, as a single character. Here is an example of writing a single character to a Java FileWriter:

FileWriter fileWriter = new FileWriter("data/output.txt");

fileWriter.write('A');

write(char[])

The Java FileWriter also has a write(char[]) method which can write an array of characters to the destination the FileWriter is connected to. The write(char[]) method returns the number of characters actually written to the FileWriter. Here is an example of writing an array of chars to a Java FileWriter:

FileWriter fileWriter = new FileWriter("data/output.txt");

char[] chars = new char[]{'A','B','C','D','E'};
fileWriter.write(chars);

Write Performance

It is faster to write an array of characters to a Java FileWriter than writing one character at a time. The speedup can be quite significant - up to 10 x higher or more. Therefore it is recommended to use the write(char[]) methods whenever possible.

The exact speedup you get depends on the underlying OS and hardware of the computer you run the Java code on. The speedup depends on issues like memory speed, hard disk speed and buffer sizes etc.

Transparent Buffering via BufferedWriter

You can get transparent buffering of bytes written to a Java FileWriter by wrapping it in a Java BufferedWriter . All bytes written to the BufferedWriter will first get buffered inside an internal byte array in the BufferedWriter. When the buffer is full, the buffer is flushed to the underlying FileWriter all at once. Here is an example of wrapping a Java FileWriter in a BufferedWriter:

int bufferSize = 8 * 1024;

Writer writer =
    new BufferedWriter(
          new FileWriter("c:\\data\\output-file.txt"),
              bufferSize
    );

You can read more about the BufferedWriter in my BufferedWriter tutorial.

flush()

The Java FileWriter's flush() method flushes all data written to the FileWriter to the underlying file. The data might be buffered in OS memory somewhere, even if your Java code has written it to the FileWriter. By calling flush() you can assure that any buffered data will be flushed (written) to disk. Here is an example of flushing data written to a Java FileWriter by calling its flush() method:

fileWriter.flush();

Closing a FileWriter

When you are finished writing characters to a Java FileWriter you should remember to close it. Closing a FileWriter is done by calling its close() method. Here is how closing a Java FileWriter looks:

fileWriter.close();

You can also use the try-with-resources construct introduced in Java 7. Here is how to use and close a FileWriter looks with the try-with-resources construct:

try(FileWriter fileWriter =
    new FileWriter("data\\filewriter.txt") ){

    fileWriter.write("data 1");
    fileWriter.write("data 2");
    fileWriter.write("data 3");

}

Notice how there is no longer any explicit close() method call to the FileWriter instance. The try-with-resources construct takes care of that.

Jakob Jenkov

Featured Videos

Java ConcurrentMap + ConcurrentHashMap

Java Generics

Java ForkJoinPool

P2P Networks Introduction

















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next