I/O Streams & Buffers π¶
Mentor's Note: Reading data from a disk is one of the slowest things a computer does. Buffering is how we "Hack" this speed limit to make our programs lightning-fast! π‘
π The Scenario: The Hose vs. The Bucket πͺ£¶
Imagine you are filling a swimming pool from a well.
- The Stream (The Hose): You carry one small cup of water at a time from the well to the pool. (Character-by-character). π¦
- The Buffer (The Big Bucket): You use a giant bucket. You fill it at the well, carry the whole bucket, and pour it into the pool in one go. π¦
- The Result: You finish the job much faster because you make fewer trips. This is exactly what a BufferedReader does for your data! β
π The Hierarchy of Streams¶
1. Byte Streams (8-bit) π’¶
Used for handling raw binary data like images or audio.
- Classes: FileInputStream, FileOutputStream.
2. Character Streams (16-bit) π‘¶
Used for handling text data (Unicode).
- Classes: FileReader, FileWriter.
3. Buffered Streams (The Accelerators) ποΈ¶
They add a "Bucket" (Memory area) to existing streams to reduce disk access.
- Classes: BufferedReader, BufferedWriter.
π¨ Visual Logic: The Buffered Path¶
graph LR
A[Hard Drive πΏ] -- "Small Drops" --> B["InputStream (Slow) β³"]
A -- "Bulk Load" --> C["Buffer (Memory) πͺ£"]
C -- "Instant Access" --> D["Your Program π"]
style C fill:#dfd,stroke:#333
π» Implementation: The Performance Lab¶
import java.io.*;
public class Main {
public static void main(String[] args) {
// π Scenario: Reading a long text file
// π Action: Wrapping FileReader inside a BufferedReader
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Processing: " + line);
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
π Sample Dry Run (BufferedReader)¶
Task: Read 1KB file
| Component | Logic | Result |
|---|---|---|
| FileReader | Ask Disk for 1 character | SLOW (Wait for hardware) β³ |
| BufferedReader | Ask Disk for 8KB chunk | FAST (One big pull) ποΈ |
| Next Line | Read from Memory | INSTANT β‘ |
π Technical Analysis¶
- Standard Buffer Size: Default is 8192 characters (8KB).
- Line Endings:
readLine()automatically handles\nor\r\nregardless of the Operating System. π
π― Practice Lab π§ͺ¶
Task: The Data Copier
Task: Write a program that reads input.txt and copies its content into a new file output.txt using Buffered Streams.
Hint: Use reader.readLine() and writer.write(). π‘
π‘ Interview Tip π¶
"Interviewers love asking: 'When should you use FileInputStream vs FileReader?' Answer: Use Stream for Binary files (Images/PDFs) and Reader for Text files (Notepad/Logs)!"
π‘ Pro Tip: "One interface, multiple implementationsβthat's the power of being flexible!" - Anonymous
β Back: Try-with-resources | Next: Collections Overview β