Java OutputStreamWriter

Jakob Jenkov
Last update: 2019-08-31

The Java OutputStreamWriter class, java.io.OutputStreamWriter, is intended to wrap an Java OutputStream and thereby turning the byte based output stream into a character based Writer. The Java OutputStreamWriter can also wrap any subclass of OutputStream.

The Java OutputStreamWriter is useful if you need to write characters to a file, encoded as e.g. UTF-8 or UTF-16. You can then write the characters (char values) to the OutputStreamWriter and it will encode them correctly and write the encoded bytes to the underlying OutputStream.

The Java OutputStreamWriter is a subclass of the Java Writer class. Thus, you can use an OutputStreamWriter anywhere a Writer is required.

OutputStreamWriter Example

Here is a simple Java OutputStreamWriterexample:

OutputStream       outputStream       = new FileOutputStream("c:\\data\\output.txt");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);

outputStreamWriter.write("Hello World");

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

Character Encoding Constructors

The Java OutputStreamWriter also has alternative constructors that allow you to specify the character set (ISO-Latin1, UTF-8, UTF-16 etc.) to use to convert the written characters to the bytes written to the underlying OutputStream. Here is a Java OutputStreamWriter example showing the use of one of these constructors:

OutputStream       outputStream       = new FileOutputStream("c:\\data\\output.txt");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");

This example creates an OutputStreamWriter that will convert all characters written to it to UTF-8 encoded characters (one or more bytes per character) and write the UTF-8 encoded bytes to the underlying OutputStream .

write(int)

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

OutputStream       outputStream       = new FileOutputStream("c:\\data\\output.txt");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");

outputStreamWriter.write('A');

write(char[])

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

OutputStream       outputStream       = new FileOutputStream("c:\\data\\output.txt");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");

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

Write Performance

It is faster to write an array of characters to a Java OutputStreamWriter 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, or network card speed and buffer sizes, depending on which destination the OutputStreamWriter sends its data to.

Transparent Buffering via BufferedWriter

You can get transparent buffering of characters written to a Java OutputStreamWriter 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 OutputStreamWriter all at once. Here is an example of wrapping a Java OutputStreamWriter in a BufferedWriter:

int bufferSize = 8 * 1024;

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

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

Transparent Buffering via BufferedOutputStream

Another way to add transparent buffering of characters written to a Java OutputStreamWriter is by wrapping the OutputStream in a Java BufferedOutputStream, before wrapping it in a OutputStreamWriter. All bytes written to the BufferedOutputStream will first get buffered inside an internal byte array in the BufferedOutputStream. When the buffer is full, the buffer is flushed to the underlying OutputStream all at once. Here is an example of using a Java OutputStreamWriter with a BufferedOutputStream:

int bufferSize = 8 * 1024;

OutputStreamWriter outputStreamWriter =
    new OutputStreamWriter(
        new BufferedOutputStream(
              new FileOutputStream("c:\\data\\output-file.txt"),
              bufferSize
        ),
        "UTF-8"
    );

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

Which of the two buffer mechanisms you want to use I will leave up to you. Perhaps experiment a bit with both options and see which one works best for you.

flush()

The Java OutputStreamWriter's flush() method flushes all data written to the OutputStreamWriter to the underlying data destination. For instance, if the OutputStreamWriter is a FileWriter then bytes written to the FileWriter may not have been fully written to disk yet. 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 (or network, or whatever else the destination of your OutputStreamWriter has). Here is an example of flushing data written to a Java OutputStreamWriter by calling its flush() method:

outputStreamWriter.flush();

Closing an OutputStreamWriter

When you are finished writing characters to the OutputStreamWriter you should remember to close it. Closing an OutputStreamWriter will also close the OutputStream instance to which the OutputStreamWriter is writing.

Closing an OutputStreamWriter is done by calling its close() method. Here is how closing an OutputStreamWriter looks:

outputStreamWriter.close();

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

OutputStream output = new FileOutputStream("data/data.bin");

try(OutputStreamWriter outputStreamWriter =
    new OutputStreamWriter(output)){

    Person person = new Person();
    person.name = "Jakob Jenkov";
    person.age  = 40;

    outputStreamWriter.writeObject(person);
}

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

Notice also that the first FileOutputStream instance is not created inside the try-with-resources block. That means that the try-with-resources block will not automatically close this FileOutputStream instance. However, when the OutputStreamWriter is closed it will also close the OutputStream instance it writes to, so the FileOutputStream instance will get closed when the OutputStreamWriter is closed.

Jakob Jenkov

Featured Videos

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