我使用此代码读取 proc 文件系统中的所有文件夹
for (Path processPath :
Files.newDirectoryStream(FileSystems.getDefault().getPath("/proc"), "[0-9]*"))
{
// Some logic
}
一段时间后我收到此错误
java.nio.file.FileSystemException: /proc: Too many open files
看起来这个循环正在打开文件而不关闭它们。有没有办法在每次循环运行后关闭文件?
最佳答案
根据 oracle Javadoc: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newDirectoryStream(java.nio.file.Path)
当不使用 try-with-resources 构造时,应在迭代完成后调用目录流的 close 方法,以便释放为打开目录保留的任何资源。你做错的是在for循环中调用newDirectoryStream,所以你不能使用它的方法。
我只是认为,你应该这样做(如果你不想使用 try-with-resources):
DirectoryStream<Path> dirStream = Files.newDirectoryStream(FileSystems.getDefault().getPath("/proc"), "[0-9]*");
for (Path processPath : dirStream)
{
// your logic
}
dirStream.close();
关于java.nio.file.FileSystemException :/proc: Too many open files,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26334421/