Skip to lesson

Decorators in Java I/O streams

Reading a file line by line in Java uses a stack of objects such as new BufferedReader(new InputStreamReader(...)). Why so many layers, and how do you read them?

Reading a java.io chain from the inside out

A source is the innermost stream that really holds or fetches the data, such as FileInputStream or StringReader.

new BufferedReader(new InputStreamReader(in, UTF_8)) is a chain of three objects. Example 1 writes the layers on separate lines so you can read the chain from the inside out.

Example 1 · BufferedReader over InputStreamReader over bytes

ReaderChainDemo.javaJava
import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.nio.charset.StandardCharsets;
public class ReaderChainDemo {    public static void main(String[] args) throws IOException {        byte[] data = "A101,1499\nA102,899\nA103,250\n".getBytes(StandardCharsets.UTF_8);
        InputStream source = new ByteArrayInputStream(data);                     // bytes        InputStreamReader chars = new InputStreamReader(source, StandardCharsets.UTF_8); // adapter        BufferedReader lines = new BufferedReader(chars);                        // decorator
        int total = 0;        String line;        while ((line = lines.readLine()) != null) {            String[] parts = line.split(",");            total += Integer.parseInt(parts[1]);            System.out.println("Order " + parts[0] + ": Rs " + parts[1]);        }        lines.close();        System.out.println("Total: Rs " + total);    }}
Output
Order A101: Rs 1499
Order A102: Rs 899
Order A103: Rs 250
Total: Rs 2648

What this code does

  • The three layers are written on separate lines here so each role is clear. Usually they are nested in one expression: new BufferedReader(new InputStreamReader(source, UTF_8)).
  • readLine() exists only on BufferedReader. It is the extra behaviour the decorator adds on top of the plain Reader interface.

Read the chain from the inside out: in is the source of bytes, InputStreamReader turns bytes into characters, and BufferedReader adds a buffer and readLine(). BufferedReader is a decorator, because it is a Reader that wraps a Reader. InputStreamReader is the adapter from the Adapter lesson, because it changes the interface from bytes to characters.

The usual layers in java.io:

  • Source: FileInputStream, ByteArrayInputStream, StringReader.
  • Adapter: InputStreamReader (bytes to chars), OutputStreamWriter (chars to bytes).
  • Decorators: BufferedReader, BufferedInputStream, DataInputStream, LineNumberReader, PushbackReader.

Order of execution

Read a chain inside out

Put the layers in the order the data passes through them.

Stacking stream decorators

DataOutputStream writes Java values such as int and boolean as bytes, and DataInputStream reads them back. Both are decorators.

Example 2 writes an order record with DataOutputStream over a BufferedOutputStream, and shows the byte count before and after close().

Example 2 · DataOutputStream over BufferedOutputStream, and the flush trap

DataStreamsDemo.javaJava
import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;
public class DataStreamsDemo {    public static void main(String[] args) throws IOException {        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (DataOutputStream out = new DataOutputStream(new BufferedOutputStream(bytes))) {            out.writeUTF("A101");      // 2 length bytes + 4 characters            out.writeInt(1499);        // 4 bytes            out.writeBoolean(true);    // 1 byte            System.out.println("Before close: " + bytes.size() + " bytes");        }        System.out.println("After close: " + bytes.size() + " bytes");
        try (DataInputStream in = new DataInputStream(                new BufferedInputStream(new ByteArrayInputStream(bytes.toByteArray())))) {            System.out.println("Read back: " + in.readUTF() + ", Rs " + in.readInt() + ", paid " + in.readBoolean());        }    }}
Output
Before close: 0 bytes
After close: 11 bytes
Read back: A101, Rs 1499, paid true

What this code does

  • Before close, all 11 bytes are still in the BufferedOutputStream's buffer, so the byte array underneath is empty. Closing the outer DataOutputStream flushes and closes every layer.
  • Reading uses the mirror chain. DataInputStream does not care whether a buffer or a file sits under it, because each layer only knows the InputStream interface.

Buffering has a classic trap. A BufferedOutputStream keeps bytes in memory until its buffer is full, flush() is called or the stream is closed. If the program ends without closing, the last bytes never reach the file.

The two layers do not know about each other, so the buffer or the source underneath can change without touching the data decorator.

Predict the output

Is the byte there yet?

A buffered stream writes into a ByteArrayOutputStream named sink. Pick the size printed.

Round 1 of 2

One byte is written, nothing else.

BufferedOutputStream out = new BufferedOutputStream(sink);
out.write(65);
System.out.println(sink.size());

FilterInputStream and FilterReader: the decorator base classes

FilterInputStream and FilterReader are the JDK base classes for decorators: they hold the wrapped stream in a field named in and forward every method to it.

FilterInputStream stores the wrapped stream in a protected field in and forwards every method to it. Example 3 extends it to count the bytes that pass through.

Example 3 · CountingInputStream: a FilterInputStream decorator

CountingStreamDemo.javaJava
import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.FilterInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.nio.charset.StandardCharsets;
class CountingInputStream extends FilterInputStream {    private long count;
    CountingInputStream(InputStream in) {        super(in);                        // FilterInputStream keeps it in the field "in"    }
    @Override    public int read() throws IOException {        int b = super.read();        if (b != -1) {            count++;        }        return b;    }
    @Override    public int read(byte[] buffer, int offset, int length) throws IOException {        int n = super.read(buffer, offset, length);        if (n > 0) {            count += n;        }        return n;    }
    long count() {        return count;    }}
public class CountingStreamDemo {    public static void main(String[] args) throws IOException {        byte[] invoice = "Pen,20\nBag,899\nMug,300\n".getBytes(StandardCharsets.UTF_8);        CountingInputStream counter = new CountingInputStream(new ByteArrayInputStream(invoice));
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(counter, StandardCharsets.UTF_8))) {            int lines = 0;            while (reader.readLine() != null) {                lines++;            }            System.out.println("Lines: " + lines);            System.out.println("Bytes read from source: " + counter.count());        }    }}
Output
Lines: 3
Bytes read from source: 23

What this code does

  • CountingInputStream overrides only the two read methods. close, available and the rest are forwarded to the wrapped stream by FilterInputStream.
  • The counter sits between the source and the adapter, so it sees every byte that the reader pulls in: 7 + 8 + 8 = 23.

FilterReader does the same for characters, and FilterOutputStream and FilterWriter cover writing.

To write your own decorator, extend the filter class and override only the methods whose behaviour changes. Override both read() and the bulk read(buffer, offset, length): wrappers such as BufferedReader call the bulk method, not the one-character one.

Writing a custom UpperCaseReader

A custom reader decorator is a FilterReader subclass that changes the characters as they pass through, such as UpperCaseReader.

UpperCaseReader extends FilterReader and turns each character into a capital before returning it. Example 4 puts it under a BufferedReader, so you still get readLine().

Example 4 · UpperCaseReader under a BufferedReader

UpperCaseReaderDemo.javaJava
import java.io.BufferedReader;import java.io.FilterReader;import java.io.IOException;import java.io.Reader;import java.io.StringReader;
class UpperCaseReader extends FilterReader {    UpperCaseReader(Reader in) {        super(in);    }
    @Override    public int read() throws IOException {        int c = super.read();        return c == -1 ? -1 : Character.toUpperCase(c);    }
    @Override    public int read(char[] buffer, int offset, int length) throws IOException {        int n = super.read(buffer, offset, length);        for (int i = offset; i < offset + n; i++) {     // n is -1 at the end: no loop            buffer[i] = Character.toUpperCase(buffer[i]);        }        return n;    }}
public class UpperCaseReaderDemo {    public static void main(String[] args) throws IOException {        String cities = "pune\nindore\nkochi\n";        try (BufferedReader reader = new BufferedReader(new UpperCaseReader(new StringReader(cities)))) {            String line;            while ((line = reader.readLine()) != null) {                System.out.println("City: " + line);            }        }    }}
Output
City: PUNE
City: INDORE
City: KOCHI

What this code does

  • BufferedReader fills its buffer through the bulk read(char[], int, int). If UpperCaseReader overrode only read(), this program would print the cities in small letters.
  • The chain mixes a JDK source (StringReader), a custom decorator and a JDK decorator. Each layer only knows that the next one is a Reader.

Because it is a Reader, it fits anywhere in a chain: over a StringReader in a test, over a file reader in real code, and under a BufferedReader.

Closing the outer stream closes the whole chain

Closing the outermost stream calls close() on every layer below it, down to the source, so only the outer stream needs try-with-resources.

Example 5 puts only the outer reader in try-with-resources. The source still reports that it was closed, and a read after the block fails.

Example 5 · One close on the outside closes the source

CloseChainDemo.javaJava
import java.io.BufferedReader;import java.io.IOException;import java.io.StringReader;
class TrackingReader extends StringReader {            // a source that reports when it closes    TrackingReader(String text) {        super(text);    }
    @Override    public void close() {        System.out.println("  source closed");        super.close();    }}
public class CloseChainDemo {    public static void main(String[] args) throws IOException {        BufferedReader outer = new BufferedReader(new TrackingReader("Order A101 packed\nOrder A101 shipped"));        try (outer) {                                      // Java 9: an effectively final variable            System.out.println("First line: " + outer.readLine());        }        System.out.println("After try");
        try {            outer.readLine();        } catch (IOException e) {            System.out.println("Read after close: " + e.getMessage());        }    }}
Output
First line: Order A101 packed
  source closed
After try
Read after close: Stream closed

What this code does

  • Only outer is in the try-with-resources, yet source closed prints: BufferedReader.close() calls close() on the reader it wraps.
  • Once closed, the chain cannot be used again. readLine() throws IOException with the message Stream closed.

Each decorator's close() closes the stream it wraps, so you do not close the inner ones yourself. After close, the chain is dead: BufferedReader.readLine() throws IOException: Stream closed.

Take care with System.in: closing a reader that wraps it closes System.in for the rest of the program.

Find the bug

Find the closing bug

Each snippet has a problem with closing. Click the line that causes it.

Reading a name works, but the Scanner later fails.

Round 1 of 2
Since Java 8, Files.newBufferedReader(path) builds the file, adapter and buffer chain for you, using UTF-8.

Next step

Check your understanding

12 quick questions