如何以递归方式列出Java中目录下的所有文件?框架是否提供任何实用程序?
我看到很多hacky实现.但没有来自框架或nio
编辑:这似乎不可能,请参阅https://bugs.openjdk.java.net/browse/JDK-8039910。
我有一个帮助类,它提供了一个Stream<Path>. 这段代码只是Files.walk对输出进行包装和排序:
public Stream<Path> getPaths(Path path) {
return Files.walk(path, FOLLOW_LINKS).sorted();
}
Run Code Online (Sandbox Code Playgroud)
由于遵循符号链接,如果文件系统中出现循环(例如 符号链接x -> .),则 中使用的代码Files.walk会抛出UncheckedIOException包装 的实例FileSystemLoopException。
在我的代码中,我想捕获此类异常,例如,只记录一条有用的消息。一旦发生这种情况,结果流可以/应该停止提供条目。
我尝试将.map(this::catchException)和添加.peek(this::catchException)到我的代码中,但在此阶段未捕获异常。
Path checkException(Path path) {
try {
logger.info("path.toString() {}", path.toString());
return path;
} catch (UncheckedIOException exception) {
logger.error("YEAH");
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
如果有的话,我如何UncheckedIOException在我的代码中捕获 an发出 a Stream<Path>,以便路径的使用者不会遇到此异常?
例如,以下代码永远不会遇到异常:
List<Path> paths = getPaths().collect(toList());
Run Code Online (Sandbox Code Playgroud)
现在,异常是由代码调用触发的collect(我可以在那里捕获异常):
java.io.UncheckedIOException: java.nio.file.FileSystemLoopException: /tmp/junit5844257414812733938/selfloop
at java.nio.file.FileTreeIterator.fetchNextIfNeeded(FileTreeIterator.java:88)
at …Run Code Online (Sandbox Code Playgroud) 我正在使用Java 8 Files.walk(..)来计算.mp3文件夹中包含的文件以及其中的所有文件夹。换句话说,我正在访问文件树的所有级别。
当我得到java.nio.file.AccessDeniedException的Stream关闭,我不希望这种行为。我需要它来忽略或打印异常并继续计算文件。下面是我使用的代码:):
/**
* Count files in a directory (including files in all sub
* directories)
*
* @param directory
* the directory to start in
* @return the total number of files
*/
public int countFiles(File dir) {
if (dir.exists())
try (Stream<Path> paths = Files.walk(Paths.get(dir.getPath()), FileVisitOption.FOLLOW_LINKS)) {
return (int) paths.filter(path -> {
// i am using something different here but i changed
// it just for the purpose of …Run Code Online (Sandbox Code Playgroud)