I'm using this code to read all folders in proc filesystem
for (Path processPath :
Files.newDirectoryStream(FileSystems.getDefault().getPath("/proc"), "[0-9]*"))
{
// Some logic
}
After some time I get this error
java.nio.file.FileSystemException: /proc: Too many open files
Looks like this loop is opening files without closing them. Is there any way to close the file after each cycle run?
According to the oracle Javadoc: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newDirectoryStream(java.nio.file.Path)
When not using the try-with-resources construct, then directory stream's close method should be invoked after iteration is completed so as to free any resources held for the open directory. What You do wrong is calling the newDirectoryStream in the for loop, so You cannot use it's methods.
I only think, You should do it that way (If You don't want to use try-with-resources):
DirectoryStream<Path> dirStream = Files.newDirectoryStream(FileSystems.getDefault().getPath("/proc"), "[0-9]*");
for (Path processPath : dirStream)
{
// your logic
}
dirStream.close();