我嘗試使用搜索一個特定的字符串一個大的文本文件(400MB)以下:如何在Java中快速搜索大文件中的字符串?
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 specialString fileName的速度。txt'。 –
如果他首先將整個文件讀入內存不會更快嗎? –
與你的文件訪問方法無關的一件很簡單的事情是'System.out.println'調用:如果你有大量的匹配,它會*實際上減慢你的執行速度,因爲你正在構建和打印一個新的'字符串'每次。當然,這不是你在這裏尋找的真正的優化。 – Mena