如何使用BufferedInputStream读取多个字节

时间:2014-06-20 05:05:30

标签: java

这是我的文字中的确切引用:

The purpose of I/O buffering is to improve system performance. 
Rather than reading a byte at a time, a large number of bytes are read together 
the first time the read() method is invoked.

但是,当我使用BufferedInputStream.read()时,我所能做的就是得到一个字节。我做错了什么,我需要做什么?

2 个答案:

答案 0 :(得分:0)

不是你,它是一次读取多个字符的流。 BufferedInputStream保留一个缓冲区,下次调用read()时,返回该缓冲区的下一个字节而不访问物理驱动器(除非缓冲区为空且下一个数据块必须是读入缓冲区。)

请注意,有些方法可以读取多个字节,但这些方法与您在问题中明确要求的差异无关。

答案 1 :(得分:0)

BufferedInputStream类有助于缓冲输入流。不是一次从网络或磁盘读取一个字节,而是一次读取一个更大的块。

您可以使用以下构造函数设置BufferedInputStream内部使用的缓冲区大小

InputStream input = new BufferedInputStream(new FileInputStream("PathOfFile"), 2 * 1024);

此示例将缓冲区大小设置为2 KB

创建BufferedInputStream时,会创建一个内部缓冲区数组。当读取或跳过来自流的字节时,内部缓冲区将根据需要从包含的输入流中重新填充,一次多个字节

相关问题