[英]Use Java to build an index of files in Windows 10
我正在 Java 中编写一个桌面应用程序来快速查找文件。 我已经使用 Java 中的 exec 命令来运行 powershell 来执行此操作,因为 Java 的 os.walk 方法似乎要慢得多。 现在生成一个文本文件大约需要 5 分钟,其中列出了我计算机上所有文件的内容(总共大约 440,000 个文件)。
这很好,但我遇到的问题是我无法更新这个文件列表。 因此,如果我在我的文件系统中更改了一些文件并想要更新我的文件列表,我就不能这么快(即增量)。 相反,我必须从头开始生成文件列表。
我知道你可以使用 git-bash 创建一个定位数据库(使用 updatedb)。 现在这是一个很棒的解决方案,但是我正在尝试创建的应用程序可能会被没有安装它的人使用。 因此,我想使用 Windows 提供的默认应用程序(即 powershell,或 Java 原生)。 我试图让这个应用程序易于使用,所以我不希望用户必须安装一堆其他依赖项。
以下代码显示了如何使用 Java 并完全避免 Powershell。 它在 memory 中构建了一个数组,并在 30 秒内将其写入文本文件(列出了 467,000 个文件)!
在 Main 或任何您想要的地方运行以下代码。 它调用 createFileList 方法。
List<Path> pathsArrayList = new ArrayList<>();
Path rootPath_obj;
rootPath_obj = Paths.get(this.configMap.get("root_path"));
createFileList(rootPath_obj);
下面是树 stream 遍历代码:
public void createFileList(Path path_in) throws IOException, AccessDeniedException {
try (DirectoryStream<Path> mystream = Files.newDirectoryStream(path_in)) {
for (Path entry : mystream) {
if (Files.isDirectory(entry)) {
createFileList(entry);
}
pathsArrayList.add(entry);
}
}
catch (AccessDeniedException ex) {
// Do nothing, just move on to the next file
}
}
现在写文件以备后用。 这是根路径树中所有文件的列表。
System.out.println("Writing database...");
try (FileWriter writer = new FileWriter(this.configMap.get("db_path"))) {
for(Path pth: pathsArrayList){
writer.write(pth.toString() + System.lineSeparator());
}
}
System.out.println("...database written.");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.