Java Writer Class
What Writer Is
java.io.Writer is the abstract base class for writing characters. It's the text counterpart of OutputStream and the mirror image of Reader.
OutputStream | Writer | |
|---|---|---|
| Unit | byte | char |
| Writes | byte[], single bytes | char[], String, single characters |
| Encoding | None — bytes are written as given | Characters are encoded to bytes when the destination is a byte stream |
| Use for | Binary data | Text |
A Writer lets text-producing code work with characters and strings only. Whether the text ends up in a UTF-8 file, a String in memory or an HTTP response is decided by which Writer it's given — the code that writes doesn't change.
The Writer Methods
| Method | Behaviour |
|---|---|
write(int c) | Writes one character (the low 16 bits of c) |
write(char[] buf) / write(char[] buf, int off, int len) | Writes characters from an array |
write(String s) / write(String s, int off, int len) | Writes a string or part of one |
append(CharSequence) / append(CharSequence, int start, int end) / append(char) | Like write, but return the writer for chaining (from Appendable) |
flush() | Pushes buffered characters toward the destination |
close() | Flushes, then releases resources |
Writer.nullWriter() (Java 11+) | A writer that discards everything |
Note the different meanings of the two ranges: write(String s, int off, int len) takes a start and a length, while append(CharSequence cs, int start, int end) takes a start and an end index. A subclass must implement write(char[], int, int), flush() and close().
import java.io.*;
public class W1 {
public static void main(String[] args) throws IOException {
StringWriter sw = new StringWriter();
try (Writer w = sw) {
w.write('J');
w.write(new char[] {'a', 'v', 'a'});
w.write(" 21 LTS", 0, 3);
w.append(" is ").append("fun", 0, 2).append('n');
}
System.out.println("StringWriter: " + sw);
StringWriter trace = new StringWriter();
try {
Integer.parseInt("12x");
} catch (NumberFormatException e) {
e.printStackTrace(new PrintWriter(trace));
}
String first = trace.toString().lines().findFirst().orElse("");
System.out.println("stack trace as text: " + first);
CharArrayWriter caw = new CharArrayWriter();
caw.write("abc");
System.out.println("CharArrayWriter: " + caw.size() + " chars " + java.util.Arrays.toString(caw.toCharArray()));
Writer.nullWriter().write("discarded");
System.out.println("nullWriter accepted text");
}
}
Output:
StringWriter: Java 21 is fun
stack trace as text: java.lang.NumberFormatException: For input string: "12x"
CharArrayWriter: 3 chars [a, b, c]
nullWriter accepted text
- The different write forms combine into one text:
J, thenava, then the first 3 characters of" 21 LTS"(21), then" is ", characters 0–2 of"fun"(fu) andn. StringWritercollects text in memory;toString()returns it. Closing it has no effect, so it can still be read after thetryblock. It's the character equivalent ofByteArrayOutputStreamand is handy for building text with code that expects aWriter, and for testing such code.- Capturing a stack trace as text is a classic use:
printStackTrace(PrintWriter)writes into theStringWriter, giving aStringyou can store in a database or attach to an error report. CharArrayWriteris similar but exposes the content as achar[].nullWriter()discards everything, useful where an API requires a writer but you don't need the output.
The Writer Family
| Class | Writes characters to | Notes |
|---|---|---|
OutputStreamWriter | Any OutputStream, encoded with a charset | The bridge from characters to bytes |
FileWriter | A file | An OutputStreamWriter over a FileOutputStream; charset and append constructors since Java 11 |
StringWriter | A StringBuffer in memory | |
CharArrayWriter | A char[] in memory | |
BufferedWriter | Another writer | Buffering and newLine() (BufferedWriter lesson) |
PrintWriter | Another writer or stream | print, println, printf; doesn't throw IOException (see checkError()) |
FilterWriter | Another writer | Base class for your own decorators |
PipedWriter | A PipedReader in another thread |
The standard way to write text to a byte destination:
Writer writer = new BufferedWriter(new OutputStreamWriter(byteStream, StandardCharsets.UTF_8));
For files, Files.newBufferedWriter(path, charset, options...) creates the same chain.
Encoding: What Happens to Characters a Charset Can't Represent
When a writer encodes characters into bytes, the chosen charset must be able to represent every character. If it can't, OutputStreamWriter silently replaces the character:
import java.io.*;
import java.nio.charset.*;
public class Enc {
public static void main(String[] args) throws IOException {
String text = "Total: ₹500";
ByteArrayOutputStream utf8 = new ByteArrayOutputStream();
try (Writer w = new OutputStreamWriter(utf8, StandardCharsets.UTF_8)) {
w.write(text);
}
System.out.println("UTF-8: " + utf8.size() + " bytes -> " + utf8.toString(StandardCharsets.UTF_8));
ByteArrayOutputStream latin = new ByteArrayOutputStream();
try (Writer w = new OutputStreamWriter(latin, StandardCharsets.ISO_8859_1)) {
w.write(text);
}
System.out.println("ISO-8859-1: " + latin.size() + " bytes -> " + latin.toString(StandardCharsets.ISO_8859_1));
CharsetEncoder strict = StandardCharsets.ISO_8859_1.newEncoder()
.onUnmappableCharacter(CodingErrorAction.REPORT)
.onMalformedInput(CodingErrorAction.REPORT);
try (Writer w = new OutputStreamWriter(new ByteArrayOutputStream(), strict)) {
w.write(text);
} catch (UnmappableCharacterException e) {
System.out.println("strict encoder: UnmappableCharacterException, input length " + e.getInputLength());
}
}
}
Output:
UTF-8: 13 bytes -> Total: ₹500
ISO-8859-1: 11 bytes -> Total: ?500
strict encoder: UnmappableCharacterException, input length 1
- UTF-8 can encode every Unicode character;
₹takes 3 bytes, so the 11 characters become 13 bytes. - ISO-8859-1 (Latin-1) covers only 256 characters and has no rupee sign.
OutputStreamWriterwrites?instead, without any error — the data is silently corrupted. - A strict
CharsetEncoderconfigured withCodingErrorAction.REPORTmakes the writer throwUnmappableCharacterExceptioninstead. Passing the encoder (rather than the charset) toOutputStreamWriteris how you get this behaviour.Files.newBufferedWriterandFiles.writeStringuse a reporting encoder internally, so they throw instead of corrupting data.
In practice: write UTF-8 unless a receiving system demands something else, and when you must use a legacy charset, use a strict encoder so that unrepresentable data is detected.
Practical Example: An HTML-Escaping Writer
Web pages often display text that users wrote — names, comments, reviews. If that text is written into HTML unchanged, a user can submit <script>...</script> and have their code run in other visitors' browsers. This attack is cross-site scripting (XSS), one of the most common web vulnerabilities. The defence is to escape HTML's special characters in every piece of untrusted text.
A FilterWriter that escapes everything passing through it makes this hard to forget: anything written to the "safe" writer is escaped automatically, while the page's own markup is written to the underlying writer directly.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.List;
public class Html {
/** Escapes every character written through it, so untrusted text can't create HTML tags. */
static class HtmlEscapingWriter extends FilterWriter {
HtmlEscapingWriter(Writer out) { super(out); }
@Override public void write(int c) throws IOException {
switch (c) {
case '<' -> out.write("<");
case '>' -> out.write(">");
case '&' -> out.write("&");
case '"' -> out.write(""");
case '\'' -> out.write("'");
default -> out.write(c);
}
}
@Override public void write(char[] buf, int off, int len) throws IOException {
for (int i = off; i < off + len; i++) write(buf[i]);
}
@Override public void write(String s, int off, int len) throws IOException {
for (int i = off; i < off + len; i++) write(s.charAt(i));
}
@Override public void close() throws IOException {
flush(); // the page writer is closed by its owner, not by us
}
}
record Review(String author, int stars, String text) { }
static void renderReviews(List<Review> reviews, Writer page) throws IOException {
Writer safe = new HtmlEscapingWriter(page);
page.write("<ul class=\"reviews\">\n");
for (Review r : reviews) {
page.write(" <li><strong>");
safe.write(r.author());
page.write("</strong> ");
page.write("★".repeat(r.stars()));
page.write("<p>");
safe.write(r.text());
page.write("</p></li>\n");
}
page.write("</ul>\n");
}
public static void main(String[] args) throws IOException {
List<Review> reviews = List.of(
new Review("Asha", 5, "Clear examples & great pace."),
new Review("<script>alert('x')</script>", 1, "Use \"try-with-resources\" <b>always</b>"));
Path file = Path.of("reviews.html");
try (Writer page = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
renderReviews(reviews, page);
}
System.out.print(Files.readString(file));
}
}
Output (the content of reviews.html):
<ul class="reviews">
<li><strong>Asha</strong> ★★★★★<p>Clear examples & great pace.</p></li>
<li><strong><script>alert('x')</script></strong> ★<p>Use "try-with-resources" <b>always</b></p></li>
</ul>
How it works:
FilterWriterstores the wrapped writer in the fieldoutand forwards calls to it. The subclass overrides all three write methods:write(int)does the escaping, and the array andStringversions route every character through it. (The defaultFilterWriterimplementations forward arrays and strings directly toout— skippingwrite(int)— so overriding onlywrite(int)would leave strings unescaped. Always check how the base class implements the methods you rely on.)- Two writers over one destination. The page markup (
<ul>,<strong>, the stars) goes topage; the user-supplied author and review text go tosafe. Both end up in the same file, in the order they're written, becauseHtmlEscapingWriterdoesn't buffer anything itself. - The five escaped characters are those that can change HTML structure:
<and>(tags),&(entities), and both quote types (attribute values). The browser displays<script>as the visible text<script>instead of running it, and shows&as&. close()only flushes. The safe writer is a view onto a writer it doesn't own; closing it would close the page writer. (Here it isn't closed at all — the page writer is closed by try-with-resources inmain.)- The page is written as UTF-8, so the
★characters are stored correctly; a real page would also declare<meta charset="UTF-8">.
Template engines such as Thymeleaf (used with Spring Boot), JSP's <c:out> and most modern frameworks escape output automatically in exactly this way. Knowing the mechanism helps you recognise the cases they don't cover — such as text placed inside a <script> block or a URL, which need different escaping rules.