emi*_*lly 3 java bufferedinputstream
我知道将 BufferedInpurStream 包裹在 FileInputStream 周围可以使读取操作更快,但试图弄清楚如何实现。我查看了 BufferedInpurStream 的源代码并得到了一些东西。这是我的理解
InputStream in = new BufferedInpurStream(new FileInputStream(filename));
int byteToRead;
while((byteToRead = in.read()) != -1)
Run Code Online (Sandbox Code Playgroud)
当我执行 bufferedInpurStream.read() 时,在内部,它会首先一次将字节块读取到缓冲区中,然后从缓冲区中一个一个地读取每个字节,而不是从文件中读取它(这会更昂贵)。一旦该缓冲区是空的,它将再次用字节块填充它
而使用 FileInputStream.read() 时,从文件中逐个字节执行读取操作,这是非常昂贵的
这种理解正确吗?
通常,read(byte[] b)(或 read(byte[] b, int off, int len))比 read() 更受青睐,因为它可能具有一些 IO 性能优势。
如果您使用 read(byte[] b),只要您使用相同的缓冲区大小,BufferedInpurStream 就没有实际优势。
void read(InputStream inputStream, int bufferSize) throws IOException
{
byte[] buffer = new byte[bufferSize];
int read;
while ((read = inputStream.read(buffer)) != -1)
{
// do some work
}
}
Run Code Online (Sandbox Code Playgroud)
和
void read2(InputStream inputStream, int bufferSize) throws IOException
{
BufferedInputStream bis = new BufferedInputStream(inputStream, bufferSize);
try
{
byte[] buffer = new byte[bufferSize];
int read;
while ((read = bis .read(buffer)) != -1)
{
// do some work
}
}
finally
{
bis.close();
}
}
Run Code Online (Sandbox Code Playgroud)
尝试阅读和阅读2。您会发现,只要使用适当的缓冲区大小,Wrapping to BufferedInputStream 就不会提高性能。(实际上它会产生另一个计算成本......)
那么,什么时候需要BufferedInputStream呢?这是我的建议:
归档时间: |
|
查看次数: |
3058 次 |
最近记录: |