不确定要如何表示树?无论如何,这是一个使用递归扫描整个子树的示例。文件和目录是相同的。请注意,File.listFiles()对于非目录返回null。
public static void main(String[] args) { Collection<File> all = new ArrayList<File>(); addTree(new File("."), all); System.out.println(all);}static void addTree(File file, Collection<File> all) { File[] children = file.listFiles(); if (children != null) { for (File child : children) { all.add(child); addTree(child, all); } }}Java
7提供了一些改进。例如,DirectoryStream一次提供一个结果-
调用者在执行操作之前不再需要等待所有I / O操作完成。这允许增量GUI更新,提前取消等。
static void addTree(Path directory, Collection<Path> all) throws IOException { try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) { for (Path child : ds) { all.add(child); if (Files.isDirectory(child)) { addTree(child, all); } } }}请注意,可怕的空返回值已由IOException代替。
Java 7还提供了一个Tree
Walker:
static void addTree(Path directory, final Collection<Path> all) throws IOException { Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { all.add(file); return FileVisitResult.CONTINUE; } });}


