allthingsare๐Ÿ…ฟ๏ธ.com Books โฌ…๏ธ Back allthingsare

โ€œThe Lord is near to the brokenhearted and saves the crushed in spirit.โ€
[Psalm 34:18]


Buffered I/O


17.2.1 Why Buffering Matters

Reading and writing one character at a time is simple but inefficient โ€” each small read/write hits the disk, which is slow.

Buffered I/O fixes this by adding a memory buffer:

  • Instead of reading one character, it reads a chunk into memory.

  • Instead of writing each character instantly, it collects them and writes in bigger blocks.

  • This reduces disk I/O calls, which speeds things up a lot, especially for large files.


Key classes:

  • BufferedReader wraps FileReader.

  • BufferedWriter wraps FileWriter.

These add powerful extra methods too:

  • BufferedReader.readLine() reads whole lines at a time.

  • BufferedWriter.newLine() safely adds platform-specific newlines.



17.2.2 Mini Lab: Buffered Read and Write

Below is an upgraded lab โ€” same as before, but using Buffered classes for faster, cleaner code.

java
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class BufferedIOMiniLab { public static void main(String[] args) { // Writing with BufferedWriter try { BufferedWriter bw = new BufferedWriter(new FileWriter("buffered_output.txt")); bw.write("Hello, Buffered I/O!"); bw.newLine(); bw.write("This writes lines efficiently."); bw.close(); System.out.println("โœ… Buffered writing done."); } catch (IOException e) { System.out.println("Error writing: " + e.getMessage()); } // Reading with BufferedReader try { BufferedReader br = new BufferedReader(new FileReader("buffered_output.txt")); String line; System.out.println("๐Ÿ“– Reading file line by line:"); while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); } catch (IOException e) { System.out.println("Error reading: " + e.getMessage()); } } }

โœ… How this works:

  • BufferedWriter wraps FileWriter, adding newLine() for portable line breaks.

  • BufferedReader makes readLine() possible โ€” very handy for parsing config files, logs, CSVs.

  • Always close buffered streams! Unflushed data can be lost if you skip .close().



17.2.3 Best Practices for File I/O

  • Always use try-catch โ€” file operations often fail (file missing, no permission, disk full).

  • Use finally or try-with-resources (try(...) {}) to ensure streams are closed automatically.

  • Prefer BufferedReader/BufferedWriter for all but the tiniest text files.

  • For binary data (images, PDFs), switch to FileInputStream and FileOutputStream + BufferedInputStream / BufferedOutputStream.