0
Description避免的Java 8 Files.walk(..)的(java.nio.file.AccessDeniedException)終止原因
我使用的Java 8Files.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 StackOverFlow question
return path.toString().contains(".mp3");
}).count();
} catch (IOException ex) {
//Main.logger.log(Level.WARNING, "", ex);
ex.printStackTrace();
}
return 0;
}
StackTrace of error:
java.io.UncheckedIOException: java.nio.file.AccessDeniedException: C:\$Recycle.B
in\S-1-5-18
at java.nio.file.FileTreeIterator.fetchNextIfNeeded(FileTreeIterator.java:88)
at java.nio.file.FileTreeIterator.hasNext(FileTreeIterator.java:104)
at java.util.Iterator.forEachRemaining(Iterator.java:115)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.jav
a:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.LongPipeline.reduce(LongPipeline.java:438)
at java.util.stream.LongPipeline.sum(LongPipeline.java:396)
at java.util.stream.ReferencePipeline.count(ReferencePipeline.java:526)
at smartcontroller.SmartController$InputService$1.countFiles(SmartController.ja
va:2092)
...
Similar question , though not the same i need a Stream to be returned .
Working around access denied in a FileWalking Tree in Java7。
使用您鏈接到 –
@JarrodRoberson我需要一個'Stream'重複的非嘗試 - 與資源版本,這樣我就可以使用Java8方法。你能發表一個關於它的答案:)? – GOXR3PLUS
你的代碼不能編譯,在try塊內部有一些亂碼(一個返回和一個count(),它指的是什麼)。請發佈一些正確的信息,讓我們正確地爲您提供幫助:) – Prim