我需要遍历网络驱动器上的目录并在层次结构中创建子级到父级的映射。一个代表性目录有 6 Terrabytes,有 900,000 个文件和 900 个文件夹。我只关心文件夹而不关心文件。出于测试目的,我将没有文件的文件夹复制到另一个网络驱动器,并在复制的版本上运行我的代码。仅迭代 900 个文件夹就可能需要 10 秒。然而,迭代原始目录结构需要 30 分钟。看起来我们正在迭代所有 900,000 个文件,尽管我们只是忽略它们。
有没有一种方法可以通过不查看文件来加快速度?如果可以的话,我更愿意坚持使用纯 Java。当通过Windows资源管理器浏览这个巨大的目录时,一点也不觉得慢。我的代码如下。
public static Map<String, String> findFolderPaths(File parentFolder) throws IOException {
Map<String, String> parentFolderMap = new HashMap<String, String>();
Files.walkFileTree(parentFolder.toPath(), new FolderMappingFileVisitor(parentFolderMap));
return parentFolderMap;
}
static class FolderMappingFileVisitor extends SimpleFileVisitor<Path> {
private Map<String, String> mapping;
FolderMappingFileVisitor(Map<String, String> map) {
this.mapping = map;
}
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs) throws IOException {
File directory = dir.toFile();
mapping.put(directory.getName(), directory.getParent());
return FileVisitResult.CONTINUE;
}
}
编辑:
我没有提到的一个重要难题是我们在 webstart 中运行该应用程序。我报告的时间来自生产,而不是开发。从 Eclipse 运行,时间比我对 FileWalker 的期望要多。
最佳答案
您使用的方法是获取BasicFileAttributes,我怀疑它正在访问每个文件的文件描述信息。
如果您只需要名称,我建议您重复/递归调用 File.listFiles();这应该只获取您要求的信息。
类似于
public static Map<String, String> findFolderPaths(File parentFolder) throws IOException {
Map<String, String> map = new HashMap<String, String>();
findFolderPaths(parentFolder, map);
return map;
}
public static void findFolderPaths(File dir, Map<String, String> map) throws IOException {
map.put(dir.getName(), dir.getPparent());
for(File file : dir.listFiles())
if (file.isDirectory())
findFolderPaths(file, map);
}
正如您所看到的,它不会做任何您不需要它做的事情。
关于java - 如何遍历大目录的目录树并忽略文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24372826/