Java 8 读取文件列表,但文件保持打开状态,直到服务器卡住

标签 java spring tomcat java-8 scheduled-tasks

这是我在调度程序上的 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);
                }
            });
    }
}

最终资源耗尽,服务器卡住。

最佳答案

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

The returned stream contains a reference to an open directory. The directory is closed by closing the stream.

例子:

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

关于Java 8 读取文件列表,但文件保持打开状态,直到服务器卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53895755/

相关文章:

java - 如何在 JBoss 6.3 EAP 上部署 Spring 管理的 JPA 应用程序

java - 在 Spring Boot 应用程序中未针对 hibernate 和 spring 过滤 Log4j2 日志级别

ubuntu - 我如何限制Tomcats同时连接?

java - 尝试访问资源 URL 时 Spring Boot 中的 Http 404

java - tomcat把web应用使用的txt文件存放在哪里

Java Reflection - 获取数组对象的大小

java - 在 Spring 中通过代理创建和初始化惰性类实例

java - find 命令不适用于 java,但适用于系统 shell

java - spring IOC,我可以删除一个遵循接口(interface)的.jar并修改app-config.xml吗?

java - spring mvc - 在重定向期间保留http header