【发布时间】:2011-02-04 14:05:14
【问题描述】:
在调试 Late-hour-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;
}
代码总结:
- 尽可能深入目录树。当一个dir中没有dir时,停止,将dir放到set中,向上遍历。不要检查集合中的目录。
- 如果到达起始路径,请停止并返回集合。
- 重复步骤 1 和 2。
前提:目录结构是有限的,数据量很小。
【问题讨论】:
-
IMO 最好是自上而下然后自下而上(就像我在下面的解决方案中一样:))。这种方式更自然,您不必将路径存储在中间级别。
-
你想做什么?您是否尝试列出所有子目录,直到达到一定级别?
-
在标题中说:“递归”但在你的代码中不是递归的?您是在寻找递归解决方案还是非递归解决方案?
FileObject的全名是什么javax.tools.FileObject -
@Oscar:自下而上递归。不是 javax.*。请阅读警告,它不完整。
标签: java recursion filesystems subdirectory