【发布时间】:2018-04-23 13:41:41
【问题描述】:
我正在编写代码来遍历我可以访问的所有文件夹。 但是,当文件夹无法访问时,我的程序会停止。
我如何绕过该文件夹并继续寻找其他人? 或者,换句话说,我如何显示我可以访问的文件夹和文件?
我正在使用 java.nio.file.Paths (Java 8)。
这是我的代码:
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Paths;
// Test File D:\TEST\test.jpg
public class TestIteration{
// Main
public static void main(String[] args) throws Exception {
// Iterate through folders
String rootFolder = "c:\\";
WalkDirTree(rootFolder); // Walks through directory tree and print names of directories/files.
}
// Prints all file/directory names in the entire directory tree
private static void WalkDirTree(String rootFolder) throws Exception {
Files.walk(Paths.get(rootFolder)).forEach(path -> {
System.out.println(path);
});
System.out.println("_______________________________________DONE");
}
}
【问题讨论】:
-
如果“停止”是指“抛出异常”,只需捕获异常并处理它。
-
在Java中方法名应该以小写开头
-
“无法访问”是什么意思?您是在谈论一个特定的例外吗?
-
我知道 lambdas 很有趣,但在这种情况下,您最好使用Files.walkFileTree,它可以让您单独处理每个文件的状态。