ignore exception and continue & counting files in a directory

℡╲_俬逩灬. 提交于 2019-12-05 02:16:55

So far, it seems Files.walk still does not play well with streams. Instead, you might want to use Files.newDirectoryStream instead. Here's some code snippet that might help.

    static class FN<T extends Path> implements Function<T, Stream<T>> {
    @Override
    public Stream<T> apply(T p) {
        if (!Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS)) {
            return Stream.of(p);
        } else {
            try {
                return toStream(Files.newDirectoryStream(p)).flatMap(q -> apply((T) q));
            } catch (IOException ex) {
                return Stream.empty();
            }
        }
    }
}

public static void main(String[] args) throws IOException {
    Path path = Paths.get("some path");
    long count = toStream(Files.newDirectoryStream(path))
            .parallel()
            .flatMap(new FN<>()::apply)
            .count();             

    System.out.println("count: " + count);
}

static <T> Stream<T> toStream(Iterable<T> iterable) {
    return StreamSupport.stream(iterable.spliterator(), false);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!