【问题标题】:find all paths under a directory查找目录下的所有路径
【发布时间】:2015-11-22 18:25:20
【问题描述】:

我需要做的就是扫描一个目录(可能包含子目录)并获取其中包含的所有路径的列表。

编辑:更改整个问题以使其更具体!

【问题讨论】:

  • Files.walkFileTree

标签: java file arraylist directory


【解决方案1】:

我的尝试是:

    try {
        List<Path> pathsInDir = new ArrayList<>();

        // Dir to scan
        DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(Paths.get("."));

        for(Path path : newDirectoryStream) {
            if(Files.isDirectory(path)) {
                pathsInDir.add(path);
                // recursive call to scan sub dir
            } else {
                // handle files.
            }
        }
    } catch (IOException e) {
        // TODO please handle the exception.
        e.printStackTrace();
    }

您可以使用java.nio.file.Path的方法来比较目录名。

【讨论】:

  • don't use the File class anymore。它已过时且信息不足。请改用Files 类。
  • 感谢小改动后效果很好!检查编辑
  • 对不起,我拒绝了编辑;)。希望你不要介意。我认为这个解决了任何一个问题......
  • 我的错.. 你的代码所做的不是我需要它做的,但它做了我的问题所要求的:p 无论如何都修复了它,所以它被接受了!
猜你喜欢
  • 2014-03-08
  • 1970-01-01
  • 2010-11-21
  • 1970-01-01
  • 2020-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
相关资源
最近更新 更多