我正在尝试使用以下内容搜索特定字符串的大文本文件(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秒内将整个文件读入内存.
>查看MD5散列速度基准测试(例如here)向我们展示了散列速率至少与磁盘读取速度一样快(通常更快).此外,字符串搜索比哈希更快,更简单并且并行化更好.
考虑到这两个估计值,我认为正确的实现可以很容易地为您提供大约10秒的运行时间(如果您在读取行批次时开始搜索作业),并且主要由您的磁盘读取时间决定.