如何在Java中快速搜索大型文件中的String?
发布时间:2020-05-25 00:22:59 所属栏目:Java 来源:互联网
导读:我正在尝试使用以下内容搜索特定字符串的大文本文件(400MB): File file = new File(fileName.txt);try { int count = 0; Scanner scanner = new Scanner(file); while(scanner.hasNextLine()) { if(scanner.nextLine(
|
我正在尝试使用以下内容搜索特定字符串的大文本文件(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);
}
解决方法首先要弄清楚实际读取整个文件内容需要多长时间,以及扫描模式所需的时间.如果您的结果由读取时间占主导地位(并且假设您正确阅读,那么频道或至少是缓冲的读者)那么没有什么可做的. 如果它占据你的扫描时间可以读取所有行,然后将要搜索的小批量行发送到工作队列,在那里你可以让多个线程拾取行批处理并在其中搜索. 球场数据 >假设硬盘读取速度为50 MB /秒(按现代标准来说速度慢),您应该能够在<10秒内将整个文件读入内存. 考虑到这两个估计值,我认为正确的实现可以很容易地为您提供大约10秒的运行时间(如果您在读取行批次时开始搜索作业),并且主要由您的磁盘读取时间决定. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
