Java Writer Class

Su Suriya Ravichandran Updated 18 Nov 2026
8 min read ·Lesson 156 of 306

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.

OutputStreamWriter
Unitbytechar
Writesbyte[], single byteschar[], String, single characters
EncodingNone — bytes are written as givenCharacters are encoded to bytes when the destination is a byte stream
Use forBinary dataText

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

MethodBehaviour
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, then ava, then the first 3 characters of " 21 LTS" ( 21), then " is ", characters 0–2 of "fun" (fu) and n.
  • StringWriter collects text in memory; toString() returns it. Closing it has no effect, so it can still be read after the try block. It's the character equivalent of ByteArrayOutputStream and is handy for building text with code that expects a Writer, and for testing such code.
  • Capturing a stack trace as text is a classic use: printStackTrace(PrintWriter) writes into the StringWriter, giving a String you can store in a database or attach to an error report.
  • CharArrayWriter is similar but exposes the content as a char[].
  • nullWriter() discards everything, useful where an API requires a writer but you don't need the output.

The Writer Family

ClassWrites characters toNotes
OutputStreamWriterAny OutputStream, encoded with a charsetThe bridge from characters to bytes
FileWriterA fileAn OutputStreamWriter over a FileOutputStream; charset and append constructors since Java 11
StringWriterA StringBuffer in memory
CharArrayWriterA char[] in memory
BufferedWriterAnother writerBuffering and newLine() (BufferedWriter lesson)
PrintWriterAnother writer or streamprint, println, printf; doesn't throw IOException (see checkError())
FilterWriterAnother writerBase class for your own decorators
PipedWriterA 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. OutputStreamWriter writes ? instead, without any error — the data is silently corrupted.
  • A strict CharsetEncoder configured with CodingErrorAction.REPORT makes the writer throw UnmappableCharacterException instead. Passing the encoder (rather than the charset) to OutputStreamWriter is how you get this behaviour. Files.newBufferedWriter and Files.writeString use 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:

  1. FilterWriter stores the wrapped writer in the field out and forwards calls to it. The subclass overrides all three write methods: write(int) does the escaping, and the array and String versions route every character through it. (The default FilterWriter implementations forward arrays and strings directly to out — skipping write(int) — so overriding only write(int) would leave strings unescaped. Always check how the base class implements the methods you rely on.)
  2. Two writers over one destination. The page markup (<ul>, <strong>, the stars) goes to page; the user-supplied author and review text go to safe. Both end up in the same file, in the order they're written, because HtmlEscapingWriter doesn't buffer anything itself.
  3. 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 &.
  4. 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 in main.)
  5. 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Writer Class and get answers drawn from it.

Signed-in readers only.