我对IO进行了一些研究,并阅读了以下关于缓冲技术的文章。为了最大限度地减少磁盘访问和底层操作系统的工作,缓冲技术使用临时缓冲区,以块方式读取数据,而不是每次读取操作都直接从磁盘读取数据。关于阅读文件和优化性能
例子没有和缓冲。
没有缓冲:
try
{
File f = new File("Test.txt");
FileInputStream fis = new FileInputStream(f);
int b; int ctr = 0;
while((b = fis.read()) != -1)
{
if((char)b== '\t')
{
ctr++;
}
}
fs.close();
// not the ideal way
} catch(Exception e)
{}
具有缓冲:
try
{
File f = new File("Test.txt");
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bs = new BufferedInputStream(fis);
int b;
int ctr = 0;
while((b =bs.read()) != -1)
{
if((char)b== '\t')
{
ctr++;
}
}
fs.close(); // not the ideal way
}
catch(Exception e){}
的结论是:
Test.txt was a 3.5MB file
Scenario 1 executed between 5200 to 5950 milliseconds for 10 test runs
Scenario 2 executed between 40 to 62 milliseconds for 10 test runs.
是否有任何其他方式做到这一点在Java中更好?或者任何其他方法/技术来提供更好的性能?请指教..!
代码格式化... HORROR!不,但是您能否正确缩进代码?它烦人的人谁愿意帮助你争取阅读你的代码。谢谢! – thatidiotguy