gpt4 book ai didi

java - 关于读取文件和优化性能

转载 作者:行者123 更新时间:2023-12-02 07:36:00 24 4
gpt4 key购买 nike

我正在对 IO 进行一些研究,并且阅读了以下有关缓冲技术的文章。为了最大限度地减少底层操作系统的磁盘访问和工作量,缓冲技术使用临时缓冲区以 block 方式读取数据,而不是在每次读取操作时直接从磁盘读取数据。

给出了没有和有缓冲的示例。

没有缓冲:

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 中还有其他更好的方法吗?或者任何其他方法/技术可以提供更好的性能?请指教..!

最佳答案

Is there any other way to do this in Java that is better? Or any other method / technique to give better performance?

就 IO 性能而言,如果没有大量其他代码,这可能是最好的。无论如何,你很可能会受到 IO 限制。

while((b =bs.read()) != -1)

逐字节读取的效率非常低。如果您正在读取文本文件,那么您应该使用 BufferedReader 来代替。这会将字节数组转换为String

BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
...
while ((String line = reader.readLine()) != null) {
...
}

此外,对于任何 IO,您应该始终在 try/finally block 中执行它以确保关闭它:

FileInputStream fis = new FileInputStream(f);
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(fis));
// once we wrap the fis in a reader, we just close the reader
} finally {
if (reader != null) {
reader.close();
}
if (fis != null) {
fis.close();
}
}

关于java - 关于读取文件和优化性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12220052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com