使用 Java 递归列出目录中的所有文件 [英] List all files from a directory recursively with Java

查看:37
本文介绍了使用 Java 递归列出目录中的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个函数,可以递归地打印目录中所有文件的名称.问题是我的代码很慢,因为每次迭代都必须访问远程网络设备.

I have this function that prints the name of all the files in a directory recursively. The problem is that my code is very slow because it has to access a remote network device with every iteration.

我的计划是首先递归加载目录中的所有文件,然后使用正则表达式遍历所有文件以过滤掉所有我不想要的文件.有人有更好的建议吗?

My plan is to first load all the files from the directory recursively and then after that go through all files with the regex to filter out all the files I don't want. Does anyone have a better suggestion?

public static printFnames(String sDir) {
    File[] faFiles = new File(sDir).listFiles();
    for (File file : faFiles) {
        if (file.getName().matches("^(.*?)")) {
            System.out.println(file.getAbsolutePath());
        }
        if (file.isDirectory()) {
            printFnames(file.getAbsolutePath());
        }
    }
}

这只是稍后的测试,我不会使用这样的代码,而是将与高级正则表达式匹配的每个文件的路径和修改日期添加到数组中.

This is just a test later on I'm not going to use the code like this, instead I'm going to add the path and modification date of every file which matches an advanced regex to an array.

推荐答案

假设这是您将要编写的实际生产代码,那么我建议使用已经解决的此类问题的解决方案 - Apache Commons IO,特别是 FileUtils.listFiles().它处理嵌套目录、过滤器(基于名称、修改时间等).

Assuming this is actual production code you'll be writing, then I suggest using the solution to this sort of thing that's already been solved - Apache Commons IO, specifically FileUtils.listFiles(). It handles nested directories, filters (based on name, modification time, etc).

例如,对于您的正则表达式:

For example, for your regex:

Collection files = FileUtils.listFiles(
  dir, 
  new RegexFileFilter("^(.*?)"), 
  DirectoryFileFilter.DIRECTORY
);

这将递归搜索与 ^(.*?) 正则表达式匹配的文件,并将结果作为集合返回.

This will recursively search for files matching the ^(.*?) regex, returning the results as a collection.

值得注意的是,这不会比滚动您自己的代码快,它在做同样的事情 - 在 Java 中拖网文件系统只是很慢.不同的是,Apache Commons 版本不会有任何错误.

It's worth noting that this will be no faster than rolling your own code, it's doing the same thing - trawling a filesystem in Java is just slow. The difference is, the Apache Commons version will have no bugs in it.

这篇关于使用 Java 递归列出目录中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆