00:00

Writer Class in Java: Writing Characters

Last updated:

Text output in Java, whether to a file, a String, an HTTP response or the console, goes through one abstract class: java.io.Writer. Code written for Writer works with every text destination.

This tutorial covers the class, its subclasses and methods, and two examples, including writing a custom Writer.

1. What Is the Writer Class in Java?

Writer is the abstract superclass of all character output streams. It writes 16-bit char values. It was added in Java 1.1 and implements Appendable, Closeable and Flushable.

Subclasses must implement three methods: write(char[] cbuf, int off, int len), flush() and close().

Declaration
public abstract class Writer implements Appendable, Closeable, Flushable

2. Writer Class Hierarchy

Writer hierarchy and methodsLeft: Writer, an abstract class implementing Appendable, Closeable and Flushable, with subclasses BufferedWriter, OutputStreamWriter (extended by FileWriter), StringWriter, PrintWriter, CharArrayWriter, PipedWriter and FilterWriter. Right: methods grouped as write (write and the chainable append), finish (the abstract flush and close) and the Java 11 factory nullWriter.Writerabstract class, implements Appendable, Closeable, FlushableBufferedWriterbufferingOutputStreamWriterchars to bytesFileWritera fileStringWritera StringPrintWriterformatted textCharArrayWritera char[]PipedWriterthreadsFilterWriterwrappersWritewrite(int), write(String)write(char[], off, len) abstractappend(...) Java 5, chainableFinishflush() abstractclose() abstractFactorynullWriter() Java 11

Swipe sideways to see the whole diagram.

3. Methods of the Writer Class

MethodDescription
void write(int c)Writes one character.
void write(String str)Writes a string.
void write(char[] cbuf, int off, int len)Writes part of a character array. Abstract.
Writer append(CharSequence csq)Writes text and returns the writer for chaining (Java 5).
void flush()Pushes buffered characters to the destination. Abstract.
void close()Flushes and releases the resource. Abstract.
static Writer nullWriter()A writer that discards everything (Java 11).

4. Example: One Method for Every Text Destination

An HR portal exports attendance as CSV. export() accepts any Writer, so the same code produces an on-screen preview and a file.

CsvExporter.java
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class CsvExporter {

    // Writes to ANY Writer: memory, file, HTTP response ...
    static void export(Writer out, String[][] rows) throws IOException {
        for (String[] row : rows) {
            out.write(String.join(",", row));
            out.write('\n');
        }
        out.flush();
    }

    public static void main(String[] args) throws IOException {
        String[][] attendance = {{"Name", "Days"}, {"Neha", "22"}, {"Vikram", "19"}};

        StringWriter preview = new StringWriter();
        export(preview, attendance);
        System.out.print(preview);

        Path file = Files.createTempFile("attendance", ".csv");
        try (Writer out = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
            export(out, attendance);
        }
        System.out.println("File matches preview: " + Files.readString(file).equals(preview.toString()));
        Files.delete(file);
    }
}
Output
Name,Days
Neha,22
Vikram,19
File matches preview: true

How the code works

  1. export() writes each row with write(String) and write(int).
  2. StringWriter keeps the preview in memory; Files.newBufferedWriter() writes the same text to a file.
  3. Reading the file back shows that both destinations hold identical text.

5. Example: Writing Your Own Writer

A payment service must never log card or phone numbers. A small Writer subclass replaces every digit with * before passing text on.

MaskingWriter.java
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

public class MaskingWriter extends Writer {
    private final Writer target;

    MaskingWriter(Writer target) {
        this.target = target;
    }

    // The three abstract methods of Writer
    @Override
    public void write(char[] cbuf, int off, int len) throws IOException {
        for (int i = off; i < off + len; i++) {
            char c = cbuf[i];
            target.write(Character.isDigit(c) ? '*' : c);   // hide every digit
        }
    }

    @Override
    public void flush() throws IOException {
        target.flush();
    }

    @Override
    public void close() throws IOException {
        target.close();
    }

    public static void main(String[] args) throws IOException {
        StringWriter log = new StringWriter();
        try (Writer out = new MaskingWriter(log)) {
            out.write("Payment by card 4111 2222 3333 4444 approved\n");
            out.append("Customer phone: 98450 12345\n");      // append() also ends up in write()
        }
        System.out.print(log);
    }
}
Output
Payment by card **** **** **** **** approved
Customer phone: ***** *****

How the code works

  1. MaskingWriter implements the three abstract methods; flush() and close() simply delegate.
  2. Every other method, including write(String) and append(), eventually calls write(char[], int, int), so one method masks all output.
  3. Closing the masking writer closes the StringWriter behind it.

6. Important Points

  • Writers that wrap a byte stream encode characters with a charset, as OutputStreamWriter does.
  • Many writers buffer text; it reaches the destination only after flush() or close().
  • append() accepts any CharSequence and returns the writer, so calls can be chained.

7. Common Mistakes and Best Practices

  • Forgetting to close or flush. Use try-with-resources so no text is lost.
  • Writing binary data with a Writer. Use an OutputStream for bytes.
  • Hard-coding \n when the platform separator is required. BufferedWriter.newLine() and PrintWriter.println() use it.
  • Relying on the default charset. Specify UTF-8 when the writer wraps a byte stream.

8. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.1Writer introduced for character output.
Java 5Implements Appendable; append() methods.
Java 7Try-with-resources through AutoCloseable.
Java 11Writer.nullWriter().
Java 25No new methods; the API above is current.

9. Summary

  • Writer is the abstract base class of every character output stream.
  • Subclasses implement write(char[], int, int), flush() and close().
  • Code that accepts a Writer can write to files, strings and network responses.
  • Close writers so buffered text is not lost.

Related Tutorials

10. Official Java Documentation References