Writer Class in Java: Writing Characters
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().
public abstract class Writer implements Appendable, Closeable, Flushable
2. Writer Class Hierarchy
Swipe sideways to see the whole diagram.
3. Methods of the Writer Class
| Method | Description |
|---|---|
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.
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);
}
}
Name,Days Neha,22 Vikram,19 File matches preview: true
How the code works
export()writes each row withwrite(String)andwrite(int).StringWriterkeeps the preview in memory;Files.newBufferedWriter()writes the same text to a file.- 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.
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);
}
}
Payment by card **** **** **** **** approved Customer phone: ***** *****
How the code works
MaskingWriterimplements the three abstract methods;flush()andclose()simply delegate.- Every other method, including
write(String)andappend(), eventually callswrite(char[], int, int), so one method masks all output. - Closing the masking writer closes the
StringWriterbehind it.
6. Important Points
- Writers that wrap a byte stream encode characters with a charset, as
OutputStreamWriterdoes. - Many writers buffer text; it reaches the destination only after
flush()orclose(). append()accepts anyCharSequenceand 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 anOutputStreamfor bytes. - Hard-coding
\nwhen the platform separator is required.BufferedWriter.newLine()andPrintWriter.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 version | Change |
|---|---|
| Java 1.1 | Writer introduced for character output. |
| Java 5 | Implements Appendable; append() methods. |
| Java 7 | Try-with-resources through AutoCloseable. |
| Java 11 | Writer.nullWriter(). |
| Java 25 | No new methods; the API above is current. |
9. Summary
Writeris the abstract base class of every character output stream.- Subclasses implement
write(char[], int, int),flush()andclose(). - Code that accepts a
Writercan write to files, strings and network responses. - Close writers so buffered text is not lost.
Related Tutorials
- Reader Class in Java
- BufferedWriter Class in Java
- StringWriter Class in Java
- PrintWriter Class in Java