簡體   English   中英

如何從Java中的多個文檔中搜索單詞?

[英]How to search a word from multiple documents in java?

我的實際要求是列出給定目錄中的所有文件,其中包含搜索短語textToMatch的最短時間約為4-5秒,其中文件數最多可以達到100000或更多。

我不需要代碼,只是我想要一個最好的算法。

由於必須打開每個文件,因此也可以使用工具構建此特定任務。 使用grep

我們有100000個文件可供查看。

% ls -l *.txt | wc -l          
100000

他們包含Vestibulum

% grep Vestibulum 1.txt        
Aenean commodo ultrices imperdiet. Vestibulum ut justo vel sapien venenatis tincidunt.
euismod ultrices facilisis. Vestibulum porta sapien adipiscing augue congue id pretium lectus

計數包含Vestibulum的文件,然后計時。

% time grep -l Vestibulum *.txt | wc -l
100000
grep --color=auto -l Vestibulum *.txt  0,28s user 0,25s system 99% cpu 0,537 total
wc -l  0,00s user 0,01s system 1% cpu 0,537 total

如您所見,這在我的計算機上僅需一秒鍾。

您的程序必須處理2個問題:

  1. 在每個子目錄中找到每個文件,
  2. 在每個文件中搜索所需的短語。

對於1:您可以迭代地或遞歸地在給定目錄中搜​​索文件,或者使用FileVisitorApache Commons IO讓Java 7或8為您完成工作。

對於2:您可以使用Java掃描儀或自行實現用於搜索內部文件的非常快速的算法,稱為Boyer-Moore算法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM