Java I/O Streams: BufferedInputStream and BufferedOutputStream
In this blog, we’ll dive into two important Java classes that help improve performance during file I/O operations: BufferedInputStream and BufferedOutputStream. These classes add buffering capabilities to reduce the number of disk accesses, making I/O operations more efficient.
1. What Are BufferedInputStream and BufferedOutputStream?#
- BufferedInputStream: Wraps an
InputStream
and adds a buffer to reduce read operations from the underlying source. - BufferedOutputStream: Wraps an
OutputStream
and adds a buffer to reduce write operations to the underlying destination.
These are especially useful when working with large files or when performance is a concern.
2. BufferedInputStream Methods (With Examples)#
● int read()
#
Reads a single byte of data. Returns -1
at the end of the file.
Example:#
Output (if input.txt contains "Buffered Stream"):#
● int read(byte[] b, int off, int len)
#
Reads up to len
bytes of data into an array b
, starting at offset off
.
Example:#
Output:#
● void close()
#
Closes the stream and releases any resources associated with it.
Example:#
Output:#
3. BufferedOutputStream Methods (With Examples)#
● void write(int b)
#
Writes a single byte to the output stream.
Example:#
Output:#
(File output.txt
contains: B
)
● void write(byte[] b, int off, int len)
#
Writes len
bytes from the array b
, starting at offset off
.
Example:#
Output:#
(File output.txt
contains: Buffered Output Example
)
● void flush()
#
Flushes the buffered output to the file. Ensures no data is stuck in memory.
Note: flush() is especially useful when writing to a stream that stays open, like network sockets or large files.
● void close()
#
Closes the stream and flushes any remaining data.
Example:#
Output:#
4. When to Use Buffered Streams?#
- Use BufferedInputStream when reading large files or doing multiple small reads.
- Use BufferedOutputStream when writing large files or frequent small writes.
- Buffering reduces interaction with the file system, improving performance.
Conclusion#
In this blog, we learned about BufferedInputStream and BufferedOutputStream — how they enhance performance by reducing direct read/write calls to disk. We covered their key methods with practical examples
In the next blog, we’ll explore Java PrintStream, which is commonly used for writing formatted data to console and files.