您的位置:首页 > Web前端

Why is using BufferedInputStream to read a file byte by byte faster than using FileInputStream

2016-11-30 20:55 459 查看
refer to http://stackoverflow.com/questions/18600331/why-is-using-bufferedinputstream-to-read-a-file-byte-by-byte-faster-than-using-f
In
FileInputStream
, the method
read()
reads a single byte. From the source code:

/**
* Reads a byte of data from this input stream. This method blocks
* if no input is yet available.
*
* @return     the next byte of data, or <code>-1</code> if the end of the
*             file is reached.
* @exception  IOException  if an I/O error occurs.
*/
public native int read() throws IOException;

This is a native call to the OS which uses the disk to read the single byte. This is a heavy operation.

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.

For example, your file is
32768
bytes long. To get all the bytes in memory with a
FileInputStream
, you will require
32768
native calls to the OS. With a
BufferedInputStream
, you will only require
4
, regardless of the number of
read()
calls you will do (still
32768
).

As to how to make it faster, you might want to consider Java 7's NIO
FileChannel
class, but I have no evidence to support this.

1upvote
 flag
Aah I see, I should have checked the API first before asking. So it's simply an 8K internal buffer. That makes sense. Thanks. As for the "more efficient" part, it's not necessary, but
I thought my code might have been overly redundant in some way. I guess it's not. – ZimZim
Sep
3 '13 at 21:59
7 
  
@user1007059 You're welcome. Note that if you used
FileInputStream
's
read(byte[], int, int)
method directly instead, with a
byte[>8192]
you wouldn't need a
BufferedInputStream
wrapping it. – Sotirios Delimanolis
Sep
4 '13 at 4:01
 
  
@SotiriosDelimanolis When to use
read()
byte by byte and when to use
read(byte[])
array of byte. As I think reading array is always better. then can you give me example where to use
read()
byte by byte OR
read(byte[])
array of byte. OR
BufferedInputStream
.? – UnKnown
Apr
1 at 13:47
 
  
@UnKnown Don't have a great example. Maybe the first byte contains some flag about the content of the file or some other metadata. I don't think anyone would ever read an entire file
using
read()
. – Sotirios Delimanolis
Apr
27 at 19:04
 
  
FileChannel read and write are faster than any other approach.github.com/RedGreenCode/UVa/blob/master/Performance‌​/…
– Harish
Sep
26 at 2:22

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐