ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume IV
  5. Stream-Based I/O
Book 1 · Volume IV — Exceptions, I/O, Serialization, Reflection & Metadata · Topic 2.1

Stream-Based I/O

Input streams, output streams, readers, writers and buffered I/O

10 min readStage 1 · Foundations11 interview questions
Prerequisites
Chapter 1 (exceptions, try-with-resources)
Covers
Input streams · Output streams · Readers · Writers · Buffered I/O
Related
2.2 File Handling · 3.2 Channels & Buffers · 4.1 Object streams · Book 5 (Decorator pattern)
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers

1Concept / Definition

In java.io, a stream is a one-directional, sequential flow of data between a program and a source or destination — a file, socket, byte array, pipe or process. (It is unrelated to the java.util.stream Stream API.) Four abstract classes define the model: InputStream and OutputStream for bytes, Reader and Writer for characters. Concrete classes connect to actual sources, and filter (decorator) classes wrap other streams to add buffering, data conversion, compression or encryption.

Four abstract roots: bytes in and out, characters in and out
Figure 1 — Four abstract roots: bytes in and out, characters in and out

2Why It Exists

Programs need one uniform way to read and write data regardless of where it lives. Java 1.0 introduced byte streams; Java 1.1 added Readers and Writers because text is not bytes — characters must be decoded using a character encoding, and ad-hoc byte-to-char conversion caused internationalisation bugs. The decorator design lets any combination of features be layered without a class explosion.

3Core Concepts

Input streams

InputStream.read() returns the next byte as an int 0–255, or −1 at end of stream — an int so that −1 can be distinguished from byte value 255. read(byte[] b, int off, int len) fills a buffer and returns the number of bytes read, which may be fewer than requested — callers must loop, or use readNBytes/readAllBytes (Java 9/11). transferTo(OutputStream) (Java 9) copies a whole stream. Concrete sources include FileInputStream, ByteArrayInputStream, socket and process streams; decorators extend FilterInputStream.

The InputStream hierarchy: sources and decorators
Figure 2 — The InputStream hierarchy: sources and decorators

Output streams

OutputStream.write(int b) writes the low 8 bits of its argument; write(byte[], int, int) writes a range. flush() pushes buffered bytes to the underlying stream and close() flushes and releases the resource. Concrete destinations include FileOutputStream (with an append flag), ByteArrayOutputStream and socket streams; decorators include BufferedOutputStream, DataOutputStream, GZIPOutputStream and CipherOutputStream. OutputStream.nullOutputStream() (Java 11) discards data.

Readers

A Reader reads 16-bit char values. InputStreamReader is the bridge from bytes to characters and should always be given an explicit charset. BufferedReader adds buffering, readLine() and lines(). StringReader and CharArrayReader read from memory. FileReader is a convenience for files; since Java 11 it accepts a charset, and since Java 18 it defaults to UTF-8 (B1V3 6.4).

Writers

A Writer writes characters. OutputStreamWriter encodes chars to bytes with a charset; BufferedWriter adds buffering and newLine(); StringWriter collects text in memory; PrintWriter adds print, println and printf but swallows IOExceptions — you must call checkError() to detect failures, which makes it risky for important output.

The character-stream classes in everyday use
Figure 3 — The character-stream classes in everyday use
Readers and writers decode and encode using a charset
Figure 4 — Readers and writers decode and encode using a charset

Buffered I/O

Each call on an unbuffered file stream can become a system call — a context switch into the kernel. Reading a file one byte at a time through FileInputStream can therefore be hundreds of times slower than reading through BufferedInputStream, which fetches 8 KB at a time and serves subsequent reads from memory. The same applies to writes, where buffering also means data is not yet on its way to the OS until flush() or close(). Bulk methods that read into your own large byte arrays, transferTo, and the NIO.2 Files helpers buffer internally.

Buffering turns millions of system calls into a few thousand
Figure 5 — Buffering turns millions of system calls into a few thousand
write, flush, close and fsync — how far has the data got?
Figure 6 — write, flush, close and fsync — how far has the data got?

4How It Works Internally

The decorator design means each wrapper holds a reference to the stream it wraps (FilterInputStream.in) and delegates, adding its behaviour on the way; closing the outermost stream closes the whole chain. BufferedInputStream keeps an internal byte array with position and count markers and supports mark/reset. File streams call native methods that issue read(2)/write(2) on a file descriptor. Charset decoding in InputStreamReader is done by a StreamDecoder using a CharsetDecoder, which handles multi-byte sequences split across buffer boundaries and replaces malformed input with U+FFFD by default.

Stacking decorators around a file stream
Figure 7 — Stacking decorators around a file stream

5APIs / Features / Syntax

NeedClass / methodNote
Read all bytesin.readAllBytes() (9)Only for bounded input
Copy a streamin.transferTo(out) (9)Buffered internally
Read exact n bytesin.readNBytes(n) (11)Loops for you
Text linesBufferedReader.lines()Lazy Stream<String>
Primitive valuesDataInputStream / DataOutputStreamBig-endian, portable
CompressionGZIPInputStream / GZIPOutputStreamCall finish() or close()
In-memoryByteArrayInputStream / ByteArrayOutputStreamNo close needed
Discard / emptyOutputStream.nullOutputStream(), InputStream.nullInputStream() (11)Testing

6Practical Examples

JAVAStreams, readers and writers in realistic code
// Copy with buffering and explicit resources
try (InputStream in = new BufferedInputStream(new FileInputStream(src));
     OutputStream out = new BufferedOutputStream(new FileOutputStream(dst))) {
    in.transferTo(out);
}

// Read a gzipped UTF-8 CSV line by line
try (BufferedReader r = new BufferedReader(new InputStreamReader(
        new GZIPInputStream(new FileInputStream("orders.csv.gz")), StandardCharsets.UTF_8))) {
    r.lines().skip(1).map(Csv::parse).forEach(importer::accept);
}

// Correct manual read loop: read() may return fewer bytes than requested
byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) != -1) {
    digest.update(buf, 0, n);          // use only the n bytes actually read
}

// Binary protocol with DataOutputStream
try (var out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()))) {
    out.writeInt(MAGIC);
    out.writeUTF(command);
    out.writeLong(timestamp);
}                                       // close() flushes the buffer

// Text output with error checking
try (var w = Files.newBufferedWriter(report, StandardCharsets.UTF_8)) {
    for (Line l : lines) { w.write(l.format()); w.newLine(); }
}
A quick guide to picking an I/O class
Figure 8 — A quick guide to picking an I/O class

7Common Problems & Mistakes

MistakeConsequenceFix
Ignoring the count returned by read(byte[])Garbage or truncated dataUse n; or readNBytes/readAllBytes
Relying on the default charset (pre-18)Mojibake across platformsAlways pass StandardCharsets.UTF_8
Unbuffered byte-at-a-time I/OVery slowBuffered* wrappers or bulk reads
Forgetting to flush/close outputTruncated filestry-with-resources
PrintWriter for critical outputSilent write failuresBufferedWriter, or check checkError()
readAllBytes on huge or unbounded inputOutOfMemoryErrorStream in chunks; set limits
Closing the inner stream onlyBuffered data lostClose the outermost wrapper

8Performance & Production Considerations

  • Buffer sizes of 8–64 KB are typical; beyond that gains are small for most workloads.
  • flush() only hands data to the OS; durability against power loss requires FileChannel.force(true) or FileDescriptor.sync() — expensive, so batch it.
  • For large file copies, Files.copy or FileChannel.transferTo can use zero-copy system calls (Chapter 3).
  • java.io streams block the calling thread; with virtual threads (Java 21+) this blocking style scales well for network I/O.
  • Set upper bounds on data read from untrusted sources (request bodies, uploads) to avoid memory exhaustion.

9Architecture & Design Considerations

The stream abstraction lets code be written against InputStream/OutputStream and work with files, sockets, cloud-storage SDK streams and in-memory buffers alike — a powerful seam for testing and for swapping storage backends. When designing APIs that consume or produce data, accept and return streams (or Paths) rather than loading everything into byte arrays, document who closes a stream, and specify encodings explicitly (UTF-8 as the default for all text interchange).

10Interview Questions & Answers

Q1L1 · BasicConcept

What are the four abstract base classes of java.io?

InputStream and OutputStream are the roots for bytes, and Reader and Writer are the roots for characters. Every class in java.io that moves data extends one of the four. Concrete subclasses connect to a real source or destination, such as FileInputStream, ByteArrayOutputStream, StringReader or a socket's streams, while filter subclasses such as BufferedInputStream, GZIPOutputStream or BufferedReader wrap another instance of the same root and add behaviour. That split is why code written against InputStream works unchanged with a file, an HTTP response body or an S3 object stream. The bridges between the two families are InputStreamReader and OutputStreamWriter, which decode and encode with a charset.

Q2L1 · BasicTricky

Why does InputStream.read() return an int?

Because it needs 257 distinct results: the 256 possible byte values plus a signal for end of stream. A Java byte is signed and ranges from -128 to 127, so returning byte would leave no value free to mean no more data. read() therefore returns an int: the byte as an unsigned value from 0 to 255, or -1 at end of stream. The gotcha is converting too early. Code that does byte b = (byte) in.read() and then tests b == -1 treats a legitimate 0xFF byte as end of file and silently truncates binary data. Keep the int, compare it with -1, and only then cast.

Q3L2 · IntermediateConcept

What is the difference between byte streams and character streams?

Byte streams move raw 8-bit data with no interpretation, which is right for images, archives, encrypted payloads, protobuf and anything else binary. Character streams move Java char values, 16-bit UTF-16 code units, and convert to and from bytes with a charset at the boundary. That conversion is the whole point: the same text is one byte per letter in ASCII, two to four bytes in UTF-8 for many scripts, and different bytes again in Windows-1252. Use Reader and Writer whenever the data is text and say which charset, normally UTF-8. Reading text through a byte stream and building strings by hand is how mojibake and split multi-byte characters appear.

Q4L2 · IntermediateConcept

What do InputStreamReader and OutputStreamWriter do?

They are the bridges between the two families. InputStreamReader wraps an InputStream and decodes its bytes into characters with a CharsetDecoder; OutputStreamWriter wraps an OutputStream and encodes characters into bytes with a CharsetEncoder. They handle the hard parts, such as a multi-byte UTF-8 sequence split across two buffer reads. Always pass the charset explicitly, as in new InputStreamReader(in, StandardCharsets.UTF_8): before Java 18 the default came from the platform, so the same code behaved differently on Windows and Linux. Note also that malformed input is replaced with U+FFFD by default, whereas Files.newBufferedReader throws MalformedInputException, which is often what a data-import job should want.

Q5L3 · Senior EngineerInternals

Why is buffering important?

Because an unbuffered file or socket stream can turn every read or write call into a system call, a switch into the kernel that costs far more than copying a few bytes in memory. Reading a 100 MB file one byte at a time through FileInputStream means about 100 million system calls; through BufferedInputStream with its default 8 KB buffer it is about 12,800, and the remaining reads are served from a Java array. Writes benefit the same way, with the caveat that buffered data has not reached the operating system until flush or close. Bulk reads into your own array, transferTo and the Files helpers achieve the same effect.

Q6L3 · Senior EngineerCode

What bug is common with read(byte[])?

Assuming that read(byte[]) filled the array. It returns the number of bytes actually read, which may be anything from 1 to the array length, and -1 at end of stream. Sockets, pipes, decompressing streams and even files near their end routinely return short reads. Code that ignores the count processes stale bytes from a previous iteration or a half-filled buffer, producing corrupt hashes, truncated messages or garbage at the end of a copy. The correct loop is while ((n = in.read(buf)) != -1) { out.write(buf, 0, n); }. When you need an exact amount, use readNBytes or DataInputStream.readFully, and transferTo for a complete copy.

Q7L3 · Senior EngineerInternals

Explain the Decorator pattern in java.io.

java.io builds features by wrapping rather than by subclassing. A filter stream such as BufferedInputStream extends FilterInputStream, holds the stream it wraps in a field, and delegates every call to it while adding its own behaviour, here an internal buffer. Because a decorator is itself an InputStream, decorators stack: new DataInputStream(new BufferedInputStream(new GZIPInputStream(new FileInputStream(f)))) reads primitives from a buffered, decompressed file. Without the pattern, every combination of source and feature would need its own class. Two consequences matter in practice: order changes behaviour, so buffer near the source and decompress above it, and closing the outermost wrapper closes and flushes the whole chain.

Q8L3 · Senior EngineerTricky

What is the difference between flush and sync?

They move data to different places. flush pushes bytes from Java-level buffers, such as a BufferedOutputStream, into the operating system with a write call; after that the data survives a crash of the JVM but usually sits in the OS page cache. sync, through FileDescriptor.sync or FileChannel.force(true), asks the OS to write those pages to the storage device and wait, so the data also survives a power loss or kernel crash. The trap is assuming that close or flush makes data durable. sync is expensive, often milliseconds per call, so databases and message brokers batch it, for example group commit, rather than forcing after every record.

Q9L4 · Technical ArchitectDesign

How would you design an API that processes large uploaded files?

Never load the whole upload into memory. The API should take an InputStream or a Path, enforce a maximum size while reading, and process the data in a single streaming pass with bounded buffers, for example parsing CSV line by line through a BufferedReader with an explicit UTF-8 charset. Large files are better staged to disk or object storage first, then processed asynchronously with a job ID the client can poll. I would also define who closes the stream, validate the content type rather than trusting the file name, compute a checksum while streaming, and make the processing resumable or idempotent so a failure at 90 percent does not mean starting again.

Q10L4 · Technical ArchitectTricky

Why is PrintWriter risky for important files?

Because PrintWriter never throws IOException from its print, write or flush methods. When the disk is full, a network share disappears or a pipe breaks, it catches the exception, sets an internal error flag and carries on, and the only way to notice is to call checkError, which most code never does. The program finishes normally and the report, export or audit file is silently truncated. PrintStream, including System.out, behaves the same way. For output that matters, use a BufferedWriter from Files.newBufferedWriter, which throws on failure, inside try-with-resources so close also reports errors. If PrintWriter's formatting is needed, call checkError before declaring success.

Q11L5 · Solution ArchitectTrade-off

How do java.io streams fit modern high-concurrency services?

Very well again, thanks to virtual threads. java.io streams block the calling thread, which used to mean one platform thread per connection and a hard ceiling of a few thousand concurrent requests, so high-concurrency servers moved to NIO and reactive frameworks. Since Java 21, a blocking read on a virtual thread parks the virtual thread and frees its carrier, so straightforward stream code scales to tens of thousands of connections, and Java 24 removed most pinning by synchronized blocks. My default today is plain blocking streams on virtual threads, as Spring Boot enables with one property, keeping NIO for custom protocol servers, memory-mapped files and zero-copy transfers.

Test your knowledge on this topic →Try multiple choice →Flashcards from this topic's 11 questions, filtered by level and type.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.