Difference between FileInputStream and BufferedInputStream in java file IO





In this post we will be discussing differences between FileInputStream  and BufferedInputStream





Difference between FileInputStream and BufferedInputStream in java file IO >


BufferedInputStream
FileInputStream
1

BufferedInputStream is buffered.
FileInputStream is not buffered.
2


So, BufferedInputStream is wrapper formed on FileInputStream.

FileInputStream fis = new FileInputStream("c:/myFile.txt");

BufferedInputStream bis = new BufferedInputStream(fis);
FileInputStream reads bytes from a file.







FileInputStream fis = new FileInputStream("c:/myFile.txt");

3
when BufferedInputStream.read() is called mostly data is read from the buffer.

When data is not available available in buffer a call is made to read system file and lot of bytes are kept in buffer.


BufferedInputStream.readLine() method reads whole line and keep it in buffer.
Every time FileInputStream.read() is called a call is made to read a system file.

FileInputStream.read()
reads 1 byte (8-bit) at a time.
4
A BufferedInputStream enables another input stream to buffer the input and supports the mark and reset methods.
An internal buffer array is created when the BufferedInputStream is created.
As bytes from the stream are read or skipped, the internal buffer is refilled as necessary from the contained input stream, many bytes at a time.
A FileInputStream obtains input bytes from a file in a file system.
And does not supports mark and reset methods.
5
BufferedInputStream is much faster as compared to FileInputStream.
FileInputStream is slower as compared to BufferedInputStream.
6
Example -
As we discussed above that when BufferedInputStream.read() is called mostly data is read from the buffer.
A BufferedInputStream reads from FileInputStream, will request lot of data from the FileInputStream (128 bytes or so… not exact figure). Thus only 2 calls will be made for reading 256 bytes from file.
Example -
As we discussed in point above that every time FileInputStream.read() is called a call is made to read a system file.

A FileInputStream will make 256 calls for reading 256 bytes from file.

Another Example - Real world Example - You must have seen youtube videos where video is buffered before you actually start watching it, buffering overall improves your video watching experience.
No buffering will make your videos watching experience a nightmare.



RELATED LINKS>

Difference between Stream (FileInputStream) and Reader (FileReader) in java file handling

Difference between FileReader and BufferedReader in java file IO

Create File using createNewFile() method in java file IO

Program to Create Directory - Single and multiple (i.e. parent and child directories) in java file IO


No comments:

Post a Comment