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

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

问题描述

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

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

  public static printFnames(String sDir){
File [] faFiles = new File (SDIR).listFiles(); (文件file:faFiles){
if(file.getName()。matches(^(。*?))){
System.out.println(file.getAbsolutePath ()); ()。

if(file.isDirectory()){
printFnames(file.getAbsolutePath());


$ b $ / code $ / pre
$ b

这只是一个测试我不打算使用这样的代码,而是要添加匹配高级正则表达式的每个文件的路径和修改日期到一个数组。

.apache.org / proper / commons-io /rel =noreferrer> Apache Commons IO ,特别是 FileUtils.listFiles() 。它处理嵌套目录,过滤器(基于名称,修改时间等)。

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

 集合文件= FileUtils.listFiles(
dir,
new RegexFileFilter(^(。*?)),
DirectoryFileFilter.DIRECTORY
);

这将递归搜索匹配 ^(。*?) regex,将结果作为一个集合返回。



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


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.

解决方案

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.

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天全站免登陆