Lesson · File I/O
I/O concepts: streams, bytes, characters and buffering
13 min readConcepts
Every I/O API in Java is one of two streams: bytes or characters. Characters are bytes plus a charset, buffering batches tiny reads into big ones, and layering small objects over each other is the design pattern that makes the whole library compose.
Input and output are directions, not device types
InputStream and OutputStream move bytes; Reader and Writer move characters. The direction is the only difference within a pair, and the source or destination is invisible to the abstraction: a file, a socket, a byte array in memory all present the same read and write methods. That is why the same layering works everywhere.
The byte and character families look parallel but mean different things. A Reader is not 'text mode'; it is a decoder that turns bytes into char values using a charset. Somewhere under every character stream there is a byte stream and a decoder, and when you forget that, you get mojibake.
| Bytes | Characters | |
|---|---|---|
| Input | InputStream (read returns int / -1) | Reader (read returns char / -1) |
| Output | OutputStream (write(byte[])) | Writer (write(String)) |
| From file | Files.newInputStream | Files.newBufferedReader |
| Bridge | bytes -> chars: InputStreamReader(bytes, charset) | chars -> bytes: OutputStreamWriter |
| Use when | binary data is the truth | text is the truth |
A character is not a byte
UTF-8 uses one to four bytes per character, so lengths and offsets differ between the two views of the same text. Decoding bytes with the wrong charset never throws: it produces replacement characters or plausible wrong letters, and the corruption is silent. ISO-8859-1, the old platform default, turns every byte into some character, which makes UTF-8 input decode to garbage without a single error.
The rule has no exceptions: name the charset at every bridge. StandardCharsets.UTF_8 is the default answer in modern Java; the machine default exists for compatibility and deserves to be treated as a bug source.
"grüß".getBytes(StandardCharsets.UTF_8).length; // 6 "grüß".getBytes(StandardCharsets.ISO_8859_1).length; // 4 new String(utf8Bytes, StandardCharsets.ISO_8859_1); // mojibake, silently
Buffering batches the tiny calls
An unbuffered read of a file asks the operating system for bytes one call at a time: every read is a system call, and the kernel round-trip dominates the actual work. A BufferedInputStream asks for a block (8 KB by default) and serves the small reads from memory. The data and the result are identical; only the number of calls changes.
Writers need the same treatment for a sharper reason: buffering means bytes sit in memory until the buffer fills, so nothing is written until flush or close. Flush pushes what is buffered now; close flushes and releases the underlying resource. Try-with-resources calls close for you, which is why wrapping output streams in it is not optional.
try (var in = new BufferedInputStream(Files.newInputStream(path))) { int b; while ((b = in.read()) != -1) { ... } // served from an 8 KB block }
The decorator pattern is the API
Concrete streams only move bytes; every capability beyond that is a wrapper that adds a concern: buffering (Buffered*), typed values (Data*), character decoding (InputStreamReader), record splitting (BufferedReader). Composition is the extension mechanism, which is why there are hundreds of stream classes and only a handful of concepts.
Read the wrapping order as a sentence: a DataInputStream over a BufferedInputStream over a FileInputStream yields typed values, buffered, from a file. Reorder and the meaning changes: buffering outside the decoder batches decoded characters; buffering inside batches raw bytes. Both are legal, and they are not equivalent.
new DataInputStream(new BufferedInputStream(Files.newInputStream(file))); // typed values <- buffered <- raw bytes from the file
Stream anatomy · the same bytes, two interpretations
the charset is the contract at this exact layer: UTF-8 bytes decoded as ISO-8859-1 turn grüß into grüà and nothing throws
Line counts live here: 18 bytes of text become two lines once the newlines are characters instead of byte values.
Resources, flush and the order of closing
Streams hold OS resources; garbage collection does not close them, it eventually finalizes without a guarantee. Try-with-resources ties closing to the block, handles suppressed exceptions when close also fails, and closes in reverse creation order so wrappers flush into their delegates before the delegate closes.
Two rules end the topic: never close the underlying stream twice (wrapping one in try-with-resources and closing both is a classic bug), and never lose output to a forgotten flush on a stream you keep open deliberately.
Checked exceptions on I/O are a feature: a missing file or a broken disk is not exceptional rare, it is an expected outcome of talking to the outside world, and callers deserve a chance to react.
Two lanes, one truth
Bytes are the truth; characters are an interpretation that requires a charset. Decide which lane your data belongs to, state the charset at every bridge, and buffer the boundaries. The rest of the I/O chapter is this idea applied to files, paths and channels.
Interview angles
InputStream versus Reader?+
InputStream reads bytes, Reader decodes bytes into characters using a charset. The extra work is invisible in the API shape but decisive for behavior: decoding with the wrong charset corrupts text silently.
Why does decoding UTF-8 as ISO-8859-1 not throw?+
ISO-8859-1 maps every byte 0-255 to a character, so any byte sequence is technically valid. You get mojibake (wrong letters), never an error. UTF-8 with malformed input replaces bad sequences instead.
What does buffering actually change?+
The number of underlying system calls, not the data. An 8 KB buffer turns many single-byte reads into few block reads. For writers it also means data may sit in memory until flush/close.
Why is try-with-resources the standard way to close streams?+
It closes reliably, including on exceptions, closes in reverse order so wrapper flushes precede delegate close, and keeps close-failures attached as suppressed exceptions instead of overwriting the original one.
What is the decorator pattern in the I/O library?+
Concrete streams move raw bytes; wrappers add capabilities (buffering, typed values, decoding, line splitting). Composition of small single-purpose wrappers replaces subclass explosion, and the wrapper order is semantically meaningful.