Skip to content
On this page

Writer

Writer is an output stream with encoding conversion, converting char to byte for output. The differences between Writer and OutputStream are as follows:

OutputStreamWriter
Byte stream, writes by byteCharacter stream, writes by char
Writes byte (0~255): void write(int b)Writes character (0~65535): void write(int c)
Writes byte array: void write(byte[] b)Writes character array: void write(char[] c)
No corresponding methodWrites String: void write(String s)

Writer is the superclass of all character output streams, providing the following main methods:

  • Write a single character (0~65535): void write(int c);
  • Write all characters from a character array: void write(char[] c);
  • Write all characters from a String: void write(String s);

FileWriter

FileWriter is a Writer that writes character streams to a file. Its usage is similar to that of FileReader:

java
try (Writer writer = new FileWriter("readme.txt", StandardCharsets.UTF_8)) {
    writer.write('H'); // Write a single character
    writer.write("Hello".toCharArray()); // Write char[]
    writer.write("Hello"); // Write String
}

CharArrayWriter

CharArrayWriter can create a Writer in memory, functioning as a buffer to write characters and ultimately produce a char[] array, similar to ByteArrayOutputStream:

java
try (CharArrayWriter writer = new CharArrayWriter()) {
    writer.write(65);
    writer.write(66);
    writer.write(67);
    char[] data = writer.toCharArray(); // { 'A', 'B', 'C' }
}

StringWriter

StringWriter is also a memory-based Writer, functioning similarly to CharArrayWriter. Internally, StringWriter maintains a StringBuffer and provides a Writer interface.

OutputStreamWriter

Besides CharArrayWriter and StringWriter, a standard Writer is actually constructed based on OutputStream, which accepts char and automatically converts it to one or more bytes, writing them to an OutputStream. Therefore, OutputStreamWriter serves as a converter that transforms any OutputStream into a Writer:

java
try (Writer writer = new OutputStreamWriter(new FileOutputStream("readme.txt"), "UTF-8")) {
    // TODO:
}

The above code is essentially an implementation of FileWriter, similar to how InputStreamReader works in the previous section.

Summary

  • Writer defines the superclass for all character output streams.
  • FileWriter implements file character stream output.
  • CharArrayWriter and StringWriter simulate character stream output in memory.
  • Always use try (resource) to ensure Writer is closed correctly.
  • Writer is based on OutputStream and can convert an OutputStream to a Writer using OutputStreamWriter, specifying the encoding during the conversion.
Writer has loaded