Video in progress

Why are streams wrapped inside each other in Java IO, for example new BufferedReader(new InputStreamReader(in))?

java.io is built on the Decorator pattern: each class adds one job. One buffers, one turns bytes into characters, one compresses. You assemble the capabilities you need by wrapping, so there is no separate class for every combination.

📖 Answer

For example, reading a gzip-compressed UTF-8 log file line by line:

try (var reader = new BufferedReader(
        new InputStreamReader(
            new GZIPInputStream(Files.newInputStream(Path.of("app.log.gz"))),
            StandardCharsets.UTF_8))) {
    reader.lines().limit(10).forEach(System.out::println);
}

From the inside out: bytes from the file → gzip unpacks → UTF-8 characters → buffer and readLine.

With inheritance you would need hundreds of classes like GzipUtf8BufferedFileReader.

When closing, it is enough to close only the outermost object: it passes close() down to the inner ones. But there is one exception: if the wrapping constructor throws (for example GZIPInputStream sees that the file is not gzip), the inner stream is left unwrapped. So the safer way is to declare each layer separately in try-with-resources.