Java:如何递归获取所有子目录?

hhh*_*hhh 6 java filesystems recursion subdirectory

在调试late-out-of-bound-recursive-function之前:是否有一个获取子目录的命令?giveMeSubDirs(downToPath)

// WARNING: RECURSION out of bound or too much data
public HashSet<FileObject> getAllDirs(String path) {
  HashSet<FileObject> checkedDirs = new HashSet<FileObject>();
  HashSet<FileObject> allDirs = new HashSet<FileObject>();

  String startingPath = path;

  File fileThing = new File(path);
  FileObject fileObject = new FileObject(fileThing);

  for (FileObject dir : getDirsInDir(path)) {

    // SUBDIR

    while ( !checkedDirs.contains(dir) 
        && !(getDirsInDir(dir.getFile().getParent()).size() == 0)) {

      // DO NOT CHECK TOP DIRS if any bottom dir UNCHECKED!

      while ( uncheckedDirsOnLevel(path, checkedDirs).size() > 0) { 

        while (getDirsInDir(path).size() == 0 
            || (numberOfCheckedDirsOnLevel(path, checkedDirs)==getDirsInDir(path).size())) {
          allDirs.add(new FileObject(new File(path)));
          checkedDirs.add(new FileObject(new File(path)));

          if(traverseDownOneLevel(path) == startingPath )
            return allDirs;

          //get nearer to the root
          path = traverseDownOneLevel(path);
        }
        path = giveAnUncheckedDir(path, checkedDirs);

        if ( path == "NoUnchecked.") {
          checkedDirs.add(new FileObject( (new File(path)).getParentFile() ));
          break;
        }
      }
    }
  }
  return allDirs;
}
Run Code Online (Sandbox Code Playgroud)

关于代码的摘要:

  1. 尽可能深入到目录树.当dir中没有dir时,停止,将dir放到set中,然后向上移动.不要检查套装中的dirs.
  2. 如果到达起始路径,请停止并返回该集.
  3. 重复步骤1和2.

PREMISE:目录结构是有限的,数据量很小.

paj*_*ton 24

您可以使用以下代码段获取所有子目录:

File file = new File("path");
File[] subdirs = file.listFiles(new FileFilter() {
    public boolean accept(File f) {
        return f.isDirectory();
    }
});
Run Code Online (Sandbox Code Playgroud)

这只能获得直接的子目录,以递归方式检索所有这些子句,你可以写:

List<File> getSubdirs(File file) {
    List<File> subdirs = Arrays.asList(file.listFiles(new FileFilter() {
        public boolean accept(File f) {
            return f.isDirectory();
        }
    }));
    subdirs = new ArrayList<File>(subdirs);

    List<File> deepSubdirs = new ArrayList<File>();
    for(File subdir : subdirs) {
        deepSubdirs.addAll(getSubdirs(subdir)); 
    }
    subdirs.addAll(deepSubdirs);
    return subdirs;
}
Run Code Online (Sandbox Code Playgroud)

  • @HH`Arrays.asList`显然返回一个不可变列表.因此,我们必须在它上面构造一个新的可变`ArrayList`. (2认同)