Java tutorials > Input/Output (I/O) and Networking > Streams and File I/O > What are buffered streams and why use them?
What are buffered streams and why use them?
Introduction to Buffered Streams
Basic Concept: Buffering
Example: Using BufferedInputStream and BufferedOutputStream
import java.io.*;
public class BufferedStreamExample {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("input.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream("output.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
int data;
while ((data = bis.read()) != -1) {
bos.write(data);
}
// bos.flush(); // Optional, but good practice to ensure all data is written
} catch (IOException e) {
e.printStackTrace();
}
}
}
Concepts behind the snippet
Real-Life Use Case
Best Practices
Interview Tip
When to use them
Memory footprint
Alternatives
Pros
Cons
FAQ
-
What is the default buffer size for BufferedInputStream and BufferedOutputStream?
The default buffer size is 8192 bytes (8KB). -
Do I need to call `flush()` on a BufferedOutputStream?
It's a good practice to call `flush()` to ensure that all buffered data is written to the underlying stream, especially before closing the stream. However, the stream will automatically be flushed when closed. -
Can I use buffered streams with network sockets?
Yes, you can wrap `InputStream` and `OutputStream` obtained from a `Socket` with `BufferedInputStream` and `BufferedOutputStream` to improve network I/O performance.