我尝试使用FileInputStream将一个大约800KB的文件读入数组,需要大约3秒钟才能将其读入内存。然后我尝试使用BufferedInputStream包装FileInputStream来执行同样的代码,这次只需要大约76毫秒。为什么使用BufferedInputStream按字节读取文件明显更快,即使我仍然是按字节读取?以下是代码(其余代码都不相关)。请注意,这是���快速”代码。如果您想获得“慢速”代码,只需删除BufferedInputStream即可:
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(file));
int[] fileArr = new int[(int) file.length()];
for (int i = 0, temp = 0; (temp = is.read()) != -1; i++) {
fileArr[i] = temp;
}
BufferedInputStream比原始输入流快30倍以上,甚至更多。那么,为什么会这样,而且有没有可能使这段代码更加高效(不使用任何外部库)?
FileInputStream
的read(byte[], int, int)
方法,并且使用大小为byte[>8192]
的数组,您就不需要使用BufferedInputStream
来包装它。 - Sotirios DelimanolisIt still returns only the single byte (but keeps the others in reserve).
时,我相信您的意思是 BufferedInputStream 仍然会从缓冲区/内存中一次读取一个字节? 如果是这样,有没有一种方法可以像使用read(byte[], int, int)
那样从内存中读取大块数据,以使读取速度更快? - emillyBufferedInputStream
会更快。BufferedInputStream
乐观地执行并读取比您需要的更多,这样当您回来时,它已经有了下一批数据。 - Sotirios Delimanolis