【发布时间】:2019-08-29 11:36:09
【问题描述】:
我正在尝试从文件夹及其子文件夹中读取文件,但在读取某些文件后,它会抛出
java.io.IOException: 打开的文件太多
我有超过 80k 的文件需要阅读。我无法关闭文件。也许我有一个错误的方法。 请引导我走向正确的道路。谢谢 这是我的Logcat
Caused by: java.io.IOException: Too many open files
at java.base/sun.nio.ch.IOUtil.makePipe(Native Method)
at java.base/sun.nio.ch.EPollSelectorImpl.<init>(EPollSelectorImpl.java:83)
at java.base/sun.nio.ch.EPollSelectorProvider.openSelector(EPollSelectorProvider.java:36)
at io.netty.channel.nio.NioEventLoop.openSelector(NioEventLoop.java:167)
代码
try (Stream<Path> filePathStream=Files.walk(Paths.get(FOLDER_PATH))) {
filePathStream.forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath.toFile().getAbsoluteFile().toString());
try {
String content = Files.readString(filePath);
System.out.println(filePath.getFileName());
JSONObject jsonObject1 = new JSONObject(content);
// System.out.println(file.getName());
HashMap yourHashMap1 = new Gson().fromJson(jsonObject1.toString(), HashMap.class);
request.add(new Config().client().prepareIndex("recipe_json", "default").setSource(yourHashMap1));
} catch (IOException ignore) {
}
【问题讨论】:
-
听起来确实是错误的做法;也就是说,此错误通常来自操作系统级别的限制。
-
@MauricePerry @snr 我使用的是 Ubuntu 18.04.3,运行上面的命令会得到
1614882 -
请提供更多的堆栈跟踪行。是什么导致
openSelector被调用? -
您标记了 java-8,但在 java-11 中引入了
Files.readString()。 -
您发布的异常不是您发布的代码抛出的。如果您不想看到您的问题被关闭,您需要解决这个问题。在我看来,您正在泄漏套接字,而不是文件。甚至可能是选择器。