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