Skip to content
Tutorials Center
My learning

Topics

Lesson 115 of 201 ยท Input and Output

Reader and Writer Classes in Depth

A tour of Java's character streams - the Reader and Writer methods, StringReader, CharArrayReader and Writer, FilterReader, InputStreamReader, PipedReader, FileReader and PrintWriter.

The previous lesson introduced character streams as the text counterpart of byte streams. This lesson opens the box. java.io.Reader and java.io.Writer are abstract classes with a small set of methods, and every concrete class (FileReader, StringWriter, PipedReader, and so on) either gives them a new data source or adds a behavior on top. Once you know the base methods and the six or seven concrete classes, you can read any text source in Java.

Here is the family tree you will walk through:

flowchart TD
    R["Reader (abstract)"] --> BR["BufferedReader"]
    R --> ISR["InputStreamReader"]
    ISR --> FR["FileReader"]
    R --> SR["StringReader"]
    R --> CAR["CharArrayReader"]
    R --> PR["PipedReader"]
    R --> FLR["FilterReader (abstract)"]
    FLR --> PBR["PushbackReader"]
    W["Writer (abstract)"] --> BW["BufferedWriter"]
    W --> OSW["OutputStreamWriter"]
    OSW --> FW["FileWriter"]
    W --> SW["StringWriter"]
    W --> CAW["CharArrayWriter"]
    W --> PW["PipedWriter"]
    W --> PRW["PrintWriter"]

Readers on top, writers below. Classes that wrap another stream (the Buffered and Filter ones) take it in their constructor.

The methods every Reader has

All readers share the same core API:

Method What it does
int read() Reads one character and returns it as an int (0-65535), or -1 at the end
int read(char[] buf) Fills as much of buf as it can and returns how many chars were read, or -1
int read(char[] buf, int off, int len) Same, but only into buf[off .. off+len-1]. This is the one abstract method; the others call it
int read(CharBuffer target) Reads into a NIO CharBuffer
long skip(long n) Discards up to n characters and returns how many it really skipped
boolean ready() true if the next read will not block
boolean markSupported(), void mark(int readAheadLimit), void reset() Remember a position and go back to it (if supported)
void close() Releases the source
long transferTo(Writer out) Copies everything that is left into a writer (Java 10+)

The return type of read() is int, not char, so that -1 can be told apart from a real character. Casting too early (char c = (char) in.read()) turns the end marker into ๏ฟฟ, and your loop never ends.

Writer mirrors this with write(int c), write(char[]), write(char[], off, len), write(String), write(String, off, len), three append methods that return the writer (so calls can be chained), flush() and close().

Java The Reader and Writer methods on in-memory classes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice write(String, off, len) takes an offset and a length, while append(CharSequence, start, end) takes a start and an end index, like substring. That mismatch trips many people up.

StringReader and StringWriter

StringReader reads from a String; StringWriter collects text in a growable buffer, and toString() gives you the result. They exist so that code written for streams (parsers, formatters, PrintWriter) can run on plain strings, which is perfect for tests. StringWriter.getBuffer() returns the live StringBuffer, so you can clear it with setLength(0). Both are examples of an in-memory stream: there is nothing to open, and close() has no effect (but calling it is still good style, and try-with-resources does it for you).

CharArrayReader and CharArrayWriter

These two do for char[] what StringReader and StringWriter do for strings.

CharArrayReader has three kinds of constructors: CharArrayReader(char[] buf) for the whole array, and CharArrayReader(char[] buf, int offset, int length) for a slice. It supports mark/reset (so markSupported() is true), and it never blocks, so ready() is true until the data is used up. The important methods are read(), read(char[], off, len), skip, mark(int) (the argument is ignored; the reader can always go back to the mark) and reset().

CharArrayWriter collects characters in an internal array that grows as needed. Its extras are toCharArray() (a copy of the data), toString(), size(), reset() (empty it without reallocating) and writeTo(Writer) to dump the content into another writer.

Java CharArrayReader and CharArrayWriter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Use these classes when an API demands a Reader or Writer but your data is already in a char[], or when you want to assemble text and then pull it out as an array.

InputStreamReader and getEncoding()

InputStreamReader is the bridge from bytes to characters. Its constructors are:

  • InputStreamReader(InputStream in): decodes with the default charset (UTF-8 since Java 18).
  • InputStreamReader(InputStream in, String charsetName), (InputStream, Charset) and (InputStream, CharsetDecoder): decode with the charset you choose. Prefer the Charset version, so you never have to catch an UnsupportedEncodingException.

Its getEncoding() method returns the historical name of the charset in use, or null once the reader is closed. You get names like UTF8 (not UTF-8) or ISO8859_1, which are not the same as the standard Charset names. Use it for logging; to compare charsets, keep your own Charset object. OutputStreamWriter has the same method. FileReader and FileWriter extend these two classes, so they inherit getEncoding(); FileReader has constructors taking a String name, a File, and (since Java 11) a Charset as an extra argument. Only the (FileDescriptor) constructor needs an already open FileInputStream; it is rare and it always uses the default charset.

Java InputStreamReader, getEncoding and FileReader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The "wrong charset" line shows why the explicit Charset matters: the two bytes of รฉ read as Latin-1 become two separate characters. More in Character Sets and Encoding.

FilterReader: adding behavior to another reader

FilterReader is an abstract base class for readers that wrap another reader and change what comes out. Its only constructor is protected FilterReader(Reader in), so you must subclass it. The wrapped reader is stored in the protected field in, and by default every method simply forwards to it. You override just the methods you want to change. (PushbackReader in the JDK is a filter reader that lets you "unread" characters; FilterWriter is the writing twin.)

Remember the two rules for a correct override: the array version read(char[], int, int) is what buffered code calls, so override it as well as read().

Java A FilterReader that upper-cases text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This is the decorator pattern you also met in Structural and Behavioral Patterns: BufferedReader and UpperCaseReader both wrap a reader and are readers themselves, so they stack in any order.

PipedReader and PipedWriter: text between threads

A pipe connects a writer in one thread to a reader in another, inside the same JVM. What one thread writes into the PipedWriter comes out of the connected PipedReader in the other thread. It is a tiny producer-consumer channel, like the byte-oriented PipedInputStream/PipedOutputStream.

  • Constructors: PipedReader() and PipedReader(int pipeSize) create an unconnected reader (the second with a buffer of that many characters; the default is 1024). PipedReader(PipedWriter src) and PipedReader(PipedWriter src, int pipeSize) connect to a writer right away. PipedWriter() and PipedWriter(PipedReader snk) do the same on the writing side. You can also join an unconnected pair with reader.connect(writer).
  • Behavior: the pipe has a fixed buffer. A writer waits when it is full, and a reader waits when it is empty. Closing the writer makes the reader see the end of the stream (-1) after it has read everything.
  • Rules: use the two ends from different threads. If one thread does both and the buffer fills, it waits for itself forever (a deadlock). If the writing thread dies without closing the writer, the reader eventually fails with IOException: Write end dead.
Java A producer thread and a consumer thread joined by a pipe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In real programs, prefer a BlockingQueue (Concurrent Collections) for passing objects between threads. Pipes are the right tool when the receiver is code that insists on a Reader (a parser, for example) while the sender is code that insists on writing to a Writer.

PrintWriter: errors you have to ask for

PrintWriter adds print, println, printf, format and append to any Writer or OutputStream. Its design choice is that none of those methods throws IOException. Instead the writer remembers that something failed:

  • boolean checkError() flushes the writer and returns true if any error has ever occurred.
  • protected void setError() marks the writer as failed (subclasses call it).
  • protected void clearError() resets the flag. Because it is protected, only a subclass can call it.

A constructor flag autoFlush (the PrintWriter(Writer, true) form) flushes after every println, printf or format, which matters when you write to a socket or the console.

Java PrintWriter swallows errors until you ask

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

If you must know that a file was written completely, use a BufferedWriter, which throws, or call checkError() before you report success.

Which class should I use?

You want to... Use
Read text from a file, quickly and correctly Files.newBufferedReader(path) (UTF-8 by default)
Read text from a String or a char[] StringReader, CharArrayReader
Decode bytes from a socket, System.in or a ZIP entry InputStreamReader with an explicit Charset
Build text in memory StringWriter, or StringBuilder if no Writer is required
Collect characters and get a char[] CharArrayWriter
Change what a reader returns a subclass of FilterReader
Hand text from one thread to another PipedWriter and PipedReader, or a queue
Format output with printf PrintWriter, and check checkError()

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does Reader.read() return an int instead of a char?

    Characters occupy 0-65535, so -1 is a value no character can have. Casting to char before checking for -1 breaks the end test.
  2. 2. What is the difference between Writer.write(String s, int off, int len) and Writer.append(CharSequence s, int start, int end)?

    write(s, off, len) writes len characters starting at off. append(s, start, end) writes the characters from start up to but excluding end, like substring.
  3. 3. What happens if one thread both writes to and reads from a connected PipedReader/PipedWriter pair and the buffer fills up?

    The writer waits for space that only the reader could free, but the same thread is the reader. Use the two ends from different threads.
  4. 4. How do you find out that a PrintWriter has failed to write something?

    PrintWriter methods do not throw IOException. The failure is remembered, and checkError() flushes the stream and reports it.
  5. 5. What do you extend to build a reader that wraps another reader and changes the characters it returns?

    FilterReader is the abstract decorator base class: its constructor takes the wrapped reader (protected field in) and forwards every call to it until you override a method.

Summary

  • Reader has read(), read(char[], off, len), skip, ready, mark/reset and close; Writer has the write overloads, append, flush and close. read() returns an int so that -1 can mean the end.
  • StringReader/StringWriter and CharArrayReader/CharArrayWriter are in-memory streams for strings and char arrays; CharArrayWriter adds toCharArray, size, reset and writeTo.
  • InputStreamReader decodes bytes with a charset; getEncoding() reports its historical name. FileReader and FileWriter are bridges with a file attached; pass a Charset explicitly.
  • Subclass FilterReader (or FilterWriter) to wrap a stream and change its behavior.
  • PipedReader and PipedWriter pass text between two threads; never use both ends from one thread.
  • PrintWriter hides IOException; use checkError() when the result matters.

Next: Directories, where you list, create and walk folders.