Java nio2 目录没有关闭。导致 "too many open files"错误

标签 java linux file tomcat centos

<分区>

我正在创建大量用于批处理的临时目录:

Path tmp = Files.createTempDirectory("tmp-images");

该目录可能包含 1-50 个图像文件。我正在使用 Apache FileUtils 处理后删除目录:

FileUtils.deleteDirectory(tmp.toFile());

目录已删除,但我遇到“太多打开的文件”。 lsof 给我这个:

java    DIR  253,0   6  136899239 /opt/tomcat/temp/tmp-images1570439806870910607 (deleted)
java    DIR  253,0   6  136899237 /opt/tomcat/temp/tmp-images2456811184361231168 (deleted)
java    DIR  253,0   6  136899237 /opt/tomcat/temp/tmp-images2456811184361231168 (deleted)
java    DIR  253,0   6  136899238 /opt/tomcat/temp/tmp-images8109733179118089091 (deleted)
java    DIR  253,0   6   69527104 /opt/tomcat/temp/tmp-images8763413559313243911 (deleted)
java    DIR  253,0   6  136927313 /opt/tomcat/temp/tmp-images8168355305097994981 (deleted)       

如何删除没有打开文件句柄的nio2临时目录?

最佳答案

我发现了错误。我用过这个:

List<Path> result = Files.list(tmp).collect(Collectors.toList());

这会使目录打开两次!

正确的做法其实是这样的:

List<Path> result;
try(Stream<Path> stream = Files.list(tmp)){
    result = stream.collect(Collectors.toList());
}

java文档:

The returned stream encapsulates a DirectoryStream. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed.

关于Java nio2 目录没有关闭。导致 "too many open files"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38652295/

相关文章:

Java 整数加法

linux - 突然我收到错误 "cannot read termcap database"

iphone - mp3 文件的 http 直播

java - 使用 JFileChooser 选择文件扩展名

java - 文件删除和重命名问题

java - FileNotFoundException 未被 IOException 捕获

javascript - 通过 javascript AJAX 发送 Java 对象

java - IntelliJ IDE for MyEclipse 中 `sout + Tab` 快捷方式的同义词

c - 如何确定进程的状态(即它是否是僵尸进程)

android - Kotlin File(path).walkTopDown() 找不到文件