Buffered Input and Output Stream in Java

In the previous tutorials, We have seen the byte streams in Java. In this tutorial, we will dive into ‘Buffered Streams’. We will come to know how to read from and write to a file in java using ‘Bufferd Streams’ and why this is a good practice to use buffered streams over byte and character streams.


Benefits of BufferedStream:

Buffered Streams provides buffering to your input/Output streams. Buffering can speed up IO quite a bit. Rather than read one byte at a time from the network or disk.

On the other hand, Buffered streams work as a wrapper to hold Unbuffered streams and make it possible to store the bunch of data or bytes in buffers (memory). The underlying OS resource is needed only when the buffer is full or empty and not on every instance of reading or writing.


BufferedInputStream Class:

Java BufferedInputStream class is used to read information from the stream. It internally uses buffer mechanism to make the performance fast. BufferedInputStream reads a larger block at a time into an internal buffer. When you read a byte from the BufferedInputStream you are therefore reading it from its internal buffer. When the buffer is fully read, the BufferedInputStream reads another larger block of data into the buffer. This is typically much faster than reading a single byte at a time from an InputStream, especially for disk access and larger data amounts.

Let’s understand this with simple example –

The above code will read the TestFile and print the content in the console. You can copy the above code and try at your local machine.


BufferedOutputStream Class:

Java BufferedOutputStream class uses an internal buffer to store data. Buffering can speed up IO quite a bit. Rather than write one byte at a time to the network or disk, you write a larger block at a time. This is typically much faster, especially for disk access and larger data amounts.

Let’s see the example of BufferedOutputStream.

The above code will write the String S into TestFile.

So we have seen the concept of Buffered Input and Output and also seen the benefits of Buffered Stream over Byte Stream.


Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.


0 Comment

Leave a Reply