我写了一个程序:
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
/**
*
* @author Mohammad Faisal
*/
public class FileContentMatcher {
public static void main(String[] args) throws IOException {
String textToMatch = "Quick Styles gallery on";
ArrayList<String> paths = new ArrayList<String>();
String content;
int found = 0;
int notFound = 0;
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File path = new File("E:\\anchit\\temp");
File[] listOfFiles = path.listFiles(filter);
for (File file : listOfFiles) {
content = FileUtils.readFileToString(file);
if (content.contains(textToMatch)) {
//System.out.println("Found in: " + file.getAbsolutePath());
paths.add(file.getAbsolutePath());
found++;
} else {
//System.out.println("No found\n" + content);
notFound++;
}
}
for (String pth : paths) {
System.out.println(pth);
}
System.out.println("Found in " + found + " files.\nNot found in " + notFound + " files.");
}
}其中我使用了undefined api。
我的实际要求是列出给定目录中的所有文件,其中包含搜索短语textToMatch,最短时间为4-5秒,其中文件的数量最多可达100000。但是这个计划需要更多的时间。
所以我需要优化这段代码,但不需要怎么做?
有什么API可以帮助我吗?我听说过Lucene,但没有弄明白如何使用它。
发布于 2013-07-15 08:56:01
作为在评论中指出,您当前的方法可能太慢,无法达到“大约4-5秒”的目标。根据实际用例的不同,使用索引确实是个好主意。这与互联网搜索引擎的做法类似。
要创建索引:
Map<String, List<File>>,用于保存搜索词与文件的关联一旦创建了索引(这可能需要相当长的时间),您只需在该索引中查找搜索单词,就可以获得包含该单词的文件列表(如果使用词干分析器,则获取包含该单词的语言变体)。
如前所述,这种方法的适用性在很大程度上取决于您的实际用例。如果文件中包含基因序列,并且您正在搜索某个模式,这可能不会有多大帮助。即使您正在搜索某个复杂的短语,这也可能不起作用,因为您必须将每个可能的(子)短语添加到索引中。但是,如果您正在寻找普通文本文件(或HTML等)中的单个单词,这可能会奏效。
更新:由于您似乎确实在搜索复杂的短语,您可以尝试以下方法:
最后,如果这仍然不能减少它,您还可以为字数大或甚至是三联字创建索引。
发布于 2013-07-15 08:22:19
以下是一些小窍门:
Reader,一次只读取一个小缓冲区,以检查是否匹配。这将改善内存使用情况,如果找到textToMatch,则避免读取整个文件。https://codereview.stackexchange.com/questions/28490
复制相似问题