Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is FileInputStream using buffers already?

When I am using FileInputStream to read an object (say a few bytes), does the underlying operation involve:

1) Reading a whole block of disk so that if I subsequently do another read operation, it wouldnt require a real disk read as that portion of the file was already fetched in the last read operation?

OR

2) A new disk access to take place because FileInputStream does not do any buffering and bufferedInputStream should have been used instead to achieve the effect of (1)?

I think that since the FileInputStream uses the read system call and it reads only a set of pages from hard disk, some buffering must be take place.

like image 563
AnkurVj Avatar asked Sep 14 '11 18:09

AnkurVj


People also ask

Is FileInputStream buffered?

BufferedInputStream is buffered, but FileInputStream is not.

When to use FileInputStream in java?

Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You can also read character-stream data. But, for reading streams of characters, it is recommended to use FileReader class.

Why is BufferedInputStream fast?

With a BufferedInputStream , the method delegates to an overloaded read() method that reads 8192 amount of bytes and buffers them until they are needed. It still returns only the single byte (but keeps the others in reserve). This way the BufferedInputStream makes less native calls to the OS to read from the file.

What does the read () method of FileInputStream return?

The read() method of a FileInputStream returns an int which contains the byte value of the byte read. If the read() method returns -1, there is no more data to read in the stream, and it can be closed. That is, -1 as int value, not -1 as byte value.


2 Answers

FileInputStream will make an underlying native system call. Most OSes will do their own buffering for this. So it does not need a real disk seek for each byte. But still, you have the cost of making the native OS call, which is expensive. So BufferedStream would be preferable. However, for reading small amounts of data (like you say, a few bytes or even kBs), either one should be fine as the number of OS calls won't be that different.

like image 131
Hari Menon Avatar answered Oct 17 '22 23:10

Hari Menon


Native code for FileInputStream is here: it doesn't look like there is any buffering going on in there. The OS buffering may kick in, but there's no explicit indicator one way or another if/when that happens.

like image 40
Femi Avatar answered Oct 17 '22 21:10

Femi