Combining Buffering with Try-With-Resources
What you'll learn: How to wrap file streams with buffered streams inside try-with-resources to guarantee proper cleanup and automatic flushing.
The Perfect Pairing
You've learned about buffering for performance and try-with-resources for automatic cleanup. Now it's time to combine these two powerful techniques. When you wrap a FileInputStream or FileOutputStream with BufferedInputStream or BufferedOutputStream inside a try-with-resources statement, Java handles both automatic flushing and closing for you—eliminating common bugs.
Why This Matters
Without try-with-resources, you might forget to close your buffered stream, leaving data stuck in the buffer and never written to disk. Or you might close streams in the wrong order. Try-with-resources solves both problems: it closes resources in reverse order of creation and automatically calls flush() before closing output streams.
The Pattern
Here's the standard pattern for buffered file copying:
try (FileInputStream fis = new FileInputStream("input.dat");
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream("output.dat");
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
// No explicit flush() or close() needed!
// Try-with-resources handles it automatically
}
When the try block completes (or if an exception occurs), Java automatically:
- Flushes
bos(pushing buffered data to disk) - Closes
bos - Closes
fos - Closes
bis - Closes
fis
Key Takeaway: Always wrap buffered streams in try-with-resources to ensure automatic flushing and proper cleanup in reverse order, preventing data loss and resource leaks.