Java 8 Path Stream和FileSystemException(打开的文件太多) [英] Java 8 Path Stream and FileSystemException (Too many open files)

查看:190
本文介绍了Java 8 Path Stream和FileSystemException(打开的文件太多)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

天才!

我正在练习Java 8.

I'm practicing Java 8.

所以,如果我做这样的事情:

So if I do something like this:

Files.walk(Paths.get(corpusPathStr))
        .filter(path -> path.toFile().isFile())
        .forEach(path -> {
            try {
                Files.lines(path)
                        .forEach(...);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

我收到FileSystemException错误.

I got FileSystemException error.

如果我在forEach下打开一个文件,可能会打开太多文件吗?

If I open a file under forEach, may too many files be opened?

还是有其他原因导致FileSystemException(打开的文件过多)?

Or are there other reasons causing FileSystemException (Too many open files)?

谢谢您的帮助!

推荐答案

使用

try(Stream<Path> stream = Files.walk(Paths.get(corpusPathStr))) {
    stream.filter(path -> Files.isRegularFile(path) && Files.isReadable(path))
          .flatMap(path -> {
                       try { return Files.lines(path); }
                       catch (IOException e) { throw new UncheckedIOException(e); }
                   })
          .forEach(...);
}
catch(UncheckedIOException ex) {
    throw ex.getCause();
}

必须正确关闭由Files.walkFiles.lines返回的流以释放资源,您可以通过try(…)构造或在flatMap操作的映射函数中返回它们来执行此操作.

The streams returned by Files.walk and Files.lines must be properly closed to release the resources, which you do by either, a try(…) construct or returning them in the mapping function of a flatMap operation.

不要使用嵌套的forEach.

UncheckedIOException不仅会被我们的映射功能抛出,还会被流实现抛出.将其转换回IOException可以平等地对待它们.

The UncheckedIOException might not only be thrown by our mapping function, but also the stream implementations. Translating it back to an IOException allows to treat them all equally.

这篇关于Java 8 Path Stream和FileSystemException(打开的文件太多)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆