首页 > 解决方案 > Java 8 读取文件列表,但文件在服务器冻结之前仍然打开使用资源

问题描述

这是我在调度程序上的 tomcat 服务器上运行的代码副本。当我检查服务器的状态时,我可以看到打开文件的数量在增加

这是用于检查打开文件的命令

sudo lsof -p $(pidof java) | grep "DIR" | wc -l

这是包含在单元测试中的代码示例。

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class OpenFilesTest {

    @Test
    public void FileRemainOpen() throws IOException {
        String path = "/data/cache/hotels/from_ivector";

        List <String> files = new ArrayList<String>();

        Files.list(Paths.get(path))
            .filter(Files::isRegularFile)
            .forEach(file -> {
                String name = file.getFileName().toString().toLowerCase();
                if (name.endsWith(".csv") || name.endsWith(".txt")) {
                    name = file.getFileName().toFile().getName();
                    files.add(name);
                }
            });
    }
}

最终资源耗尽,服务器冻结。

标签: javaspringtomcatjava-8scheduled-tasks

解决方案


您应该Stream在完成后关闭。来自的Javadoc Files.list

返回的流包含对打开目录的引用。通过关闭流来关闭目录。

例子:

try (Stream<Path> stream = Files.list(directory)) {
    // use the stream...
}

推荐阅读