I have the code below, which simply reads all the files from a folder. There are 20,000 files in this folder. The code works good on a local folder (d:/files), but fails on a network path (//robot/files) after reading about 1,000 – 2,000 files.
Update: the folders are copies of each other.
What causes this problem and how to fix it?
package cef_debug;
import java.io.*;
public class Main {
public static void main(String[] args) throws Throwable {
String folder = args[0];
File[] files = (new File(folder)).listFiles();
String line;
for (int i = 0; i < files.length; i++) {
BufferedReader br = new BufferedReader(new FileReader(files[i]));
while ((line = br.readLine()) != null) {
}
br.close();
}
}
}
I get the following error when reading from a network path (//robot/files):
Exception in thread "main" java.io.IOException: Too many open files
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.io.FileReader.<init>(FileReader.java:55)
at cef_debug.Main.main(Main.java:12)
Java Result: 1
Line 12 is the line:
BufferedReader br = new BufferedReader(new FileReader(files[i]));
There is a documented bug for some java versions and some file opens to hit a limit of 2035. It is possible that you might’ve just hit that.
From the comments:
Now, this is an old issue fixed quite some time ago, but it is possible that they would be using the same function on network access, where the bug could still exist.
Even without closing the handle or the stream, windows should be able to open >10000 file handles and keep them open, as demonstrated by this test code in the bug comments:
You could test running it on the network share, and report a bug if it fails. You could also try with a different JDK. At least with OpenJDK source, I couldn’t see any other calls except WinAPI calls, so I’d try if the behaviour is the same.