【发布时间】:2016-08-23 08:49:34
【问题描述】:
我正在尝试使用以下内容在大型文本文件 (400MB) 中搜索特定字符串:
File file = new File("fileName.txt");
try {
int count = 0;
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()) {
if(scanner.nextLine().contains("particularString")) {
count++;
System.out.println("Number of instances of String: " + count);
}
}
} catch (FileNotFoundException e){
System.out.println(e);
}
这适用于小文件,但对于这个特定文件和其他大文件来说,它需要的时间太长(>10 分钟)。
最快、最有效的方法是什么?
我现在已更改为以下内容,并在几秒钟内完成 -
try {
int count = 0;
FileReader fileIn = new FileReader(file);
BufferedReader reader = new BufferedReader(fileIn);
String line;
while((line = reader.readLine()) != null) {
if((line.contains("particularString"))) {
count++;
System.out.println("Number of instances of String " + count);
}
}
}catch (IOException e){
System.out.println(e);
}
【问题讨论】:
-
与
grep -c particularString fileName.txt比较速度。 -
如果他先把整个文件读入内存不是更快吗?
-
与您的文件访问方法无关的一件非常琐碎的事情是
System.out.println调用:如果您有大量匹配项,它会实际上减慢您的执行速度,当您每次都在构建和打印一个新的String时。当然,这不是您在这里寻找的真正优化。 -
@membersound 并行读取?你不会受到磁盘IO的限制吗?
标签: java io java.util.scanner