Byte Streams, Character Streams & Buffered I/O
Understand java.io byte vs character streams, buffering for performance, and closing streams automatically with try-with-resources.
- Byte Streams (`InputStream`, `OutputStream`): Read and write raw 8-bit bytes (
0–255). Always use these for binary files (images, PDFs, ZIP archives, audio). - Character Streams (`Reader`, `Writer`): Read and write 16-bit Unicode characters and handle character encoding/decoding automatically. Always specify
StandardCharsets.UTF_8explicitly instead of relying on the OS default charset.
Introduction
java.io models input and output as sequential streams of bytes or characters. Understanding the difference between unbuffered OS calls and buffered decorators is critical for I/O performance.
Byte Streams vs Character Streams
- Byte Streams (`InputStream`, `OutputStream`): Read and write raw 8-bit bytes (
0–255). Always use these for binary files (images, PDFs, ZIP archives, audio). - Character Streams (`Reader`, `Writer`): Read and write 16-bit Unicode characters and handle character encoding/decoding automatically. Always specify
StandardCharsets.UTF_8explicitly instead of relying on the OS default charset.
Buffering & the Decorator Pattern
Reading 1 byte at a time via FileInputStream.read() triggers an expensive OS kernel system call on every single byte! Wrapping it in BufferedInputStream or BufferedReader reads an 8 KB block into user-space memory at once, speeding up file processing by 10x–100x.
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)