我有一个网络关联存储,其中约有 500 万个 txt 文件与约 300 万笔交易相关。总数据的大小约为 3.5 TB。我必须在该位置搜索以查找交易相关文件是否可用,并且必须制作两个单独的报告作为“可用文件”和“不可用文件”的 CSV 文件。我们是 仍然在 JAVA 6 中。我面临的挑战是因为我必须递归地搜索该位置,由于尺寸巨大,我平均需要大约 2 分钟才能在该位置进行搜索。我正在使用 Java I/O API 进行递归搜索,如下所示。有什么办法可以提高性能吗?
File searchFile(File location, String fileName) {
if (location.isDirectory()) {
File[] arr = location.listFiles();
for (File f : arr) {
File found = searchFile(f, fileName);
if (found != null)
return found;
}
} else {
if (location.getName().equals(fileName)) {
return location;
}
}
return null;
}
最佳答案
您应该采用不同的方法,而不是每次搜索文件时都遍历整个目录,您应该创建一个索引,它是从文件名到文件位置的映射。
本质上:
void buildIndex(Map index, File baseDir) {
if (location.isDirectory()) {
File[] arr = location.listFiles();
for (File f : arr) {
buildIndex(index, f);
}
} else {
index.put(f.getName(), f);
}
}
既然您已经有了索引,搜索文件就变得微不足道了。
现在你已经把文件放在一个Map中了,你甚至可以使用Set操作来找到交集:
Map index = new HashMap();
buildIndex(index, ...);
Set fileSet = index.keySet();
Set transactionSet = ...;
Set intersection = new HashSet(fileSet);
fileSet.retainAll(transactionSet);
可选地,如果索引本身太大而无法保存在内存中,您可能希望在 SQLite 数据库中创建索引。
关于java - 在文件系统中搜索数据的性能优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53366609/