00:00

OutputStreamWriter Class in Java: From Characters to Bytes

Last updated:

When a program sends text over a network or saves it through a byte stream, the characters must first be encoded into bytes. OutputStreamWriter does that conversion: you write characters, and it writes the encoded bytes to an OutputStream.

This tutorial covers its constructors and methods, and two examples: sending a message and comparing the size of the same text in different charsets.

1. What Is OutputStreamWriter in Java?

OutputStreamWriter extends Writer and wraps an OutputStream. Each write() runs the charset encoder, and the resulting bytes are collected in a buffer before being written to the stream. It was added in Java 1.1 and is the parent class of FileWriter.

2. OutputStreamWriter Class Hierarchy

OutputStreamWriter class hierarchyOutputStreamWriter extends the abstract class Writer, which extends Object, and implements Appendable, Closeable, Flushable and AutoCloseable. It encodes characters into bytes; the bytes can go to System.out, a socket output stream or a FileOutputStream.ObjectextendsWriterabstract classextendsOutputStreamWriterencodes characters into bytesAppendableCloseableFlushableAutoCloseableimplementsBytes go toSystem.outsocket.getOutputStream()FileOutputStream

Swipe sideways to see the whole diagram.

3. Constructors of OutputStreamWriter

ConstructorDescription
OutputStreamWriter(OutputStream out, Charset cs)Encodes with the given charset (Java 1.4). The recommended form.
OutputStreamWriter(OutputStream out, String charsetName)Charset by name; throws UnsupportedEncodingException for unknown names.
OutputStreamWriter(OutputStream out, CharsetEncoder enc)Uses an encoder you configure yourself (Java 1.4).
OutputStreamWriter(OutputStream out)Uses the default charset (UTF-8 since Java 18).

4. Commonly Used Methods

MethodDescription
void write(int c)Encodes and writes one character.
void write(String str, int off, int len)Encodes and writes part of a string.
void flush()Writes the encoded bytes to the stream and flushes it.
String getEncoding()The charset name in use, possibly a historical name.
void close()Flushes and closes the wrapped stream.

5. Example: Sending Text over a Connection

An order system sends a status message to a client. The text contains an em dash, which takes three bytes in UTF-8.

MessageSender.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;

public class MessageSender {
    public static void main(String[] args) throws IOException {
        OutputStream socket = new ByteArrayOutputStream();   // stands in for a network connection
        String message = "Hello from Bengaluru — order #4521 is ready";   // contains an em dash

        try (OutputStreamWriter out = new OutputStreamWriter(socket, StandardCharsets.UTF_8)) {
            out.write(message);
            out.flush();                                      // push the encoded bytes to the socket
            System.out.println("Encoding:   " + out.getEncoding());
        }
        System.out.println("Characters: " + message.length());
        System.out.println("Bytes sent: " + ((ByteArrayOutputStream) socket).size());
    }
}
Output
Encoding:   UTF8
Characters: 43
Bytes sent: 45

How the code works

  1. A ByteArrayOutputStream stands in for the socket.
  2. write(message) encodes the 43 characters; flush() pushes the bytes into the stream.
  3. 45 bytes arrive, because the em dash needs three bytes instead of one.

6. Example: One Text, Different Charsets

A label printer supports several charsets. This program measures how many bytes the same 11-character price label needs in each.

CharsetSizes.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class CharsetSizes {

    static int encodedSize(String text, Charset charset) throws IOException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (Writer out = new OutputStreamWriter(bytes, charset)) {
            out.write(text);
        }
        return bytes.size();
    }

    public static void main(String[] args) throws IOException {
        String label = "Price: ₹499";                       // 11 characters, with the rupee sign
        System.out.println("Characters:  " + label.length());
        System.out.println("UTF-8:       " + encodedSize(label, StandardCharsets.UTF_8) + " bytes");
        System.out.println("UTF-16BE:    " + encodedSize(label, StandardCharsets.UTF_16BE) + " bytes");
        System.out.println("UTF-16:      " + encodedSize(label, StandardCharsets.UTF_16) + " bytes (includes a 2-byte BOM)");
        System.out.println("ISO-8859-1:  " + encodedSize(label, StandardCharsets.ISO_8859_1) + " bytes (rupee sign replaced by ?)");
    }
}
Output
Characters:  11
UTF-8:       13 bytes
UTF-16BE:    22 bytes
UTF-16:      24 bytes (includes a 2-byte BOM)
ISO-8859-1:  11 bytes (rupee sign replaced by ?)

How the code works

  1. UTF-8 uses 1 byte per English character and 3 for the rupee sign: 13 bytes.
  2. UTF-16 uses 2 bytes per character; plain UTF_16 also writes a 2-byte byte-order mark, while UTF_16BE does not.
  3. ISO-8859-1 cannot represent the rupee sign, so the writer replaces it with ?. Information is lost silently.

7. Common Mistakes and Best Practices

  • Forgetting to flush. Encoded bytes wait in a buffer; flush or close the writer.
  • Writing many small pieces without buffering. Wrap it in a BufferedWriter.
  • Choosing a charset that cannot represent your text. Unmappable characters become ?; use UTF-8.
  • Mixing charsets between writer and reader. Read with the charset you wrote with.

8. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.1OutputStreamWriter introduced.
Java 1.4Constructors that take a Charset or CharsetEncoder.
Java 18UTF-8 becomes the default charset (JEP 400).
Java 25No API changes.

9. Summary

  • OutputStreamWriter encodes characters into bytes for any OutputStream.
  • Always pass a charset, preferably UTF-8.
  • Flush or close it so buffered bytes are written.
  • It is the parent class of FileWriter.

Related Tutorials

10. Official Java Documentation References