Java
Module 18: Java I/O StreamsBeginner22 min read

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.

Key Takeaways & Core Concepts
  • 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_8 explicitly 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.

BufferedReader with Try-With-Resources
1import java.io.BufferedReader;
2import java.io.IOException;
3import java.io.StringReader;
4
5public class Main {
6 public static void main(String[] args) throws IOException {
7 String data = "Line 1: Java I/O\nLine 2: BufferedReader";
8 try (BufferedReader reader = new BufferedReader(new StringReader(data))) {
9 String line;
10 while ((line = reader.readLine()) != null) {
11 System.out.println(line);
12 }
13 }
14 }
15}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
15 lines
Note: Try-with-resources invokes `reader.close()` automatically even when exceptions occur.

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_8 explicitly 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.

Practice & AssessmentJava Programming Tutorial

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)