Peter Penzov
Peter Penzov

Reputation: 1678

java.nio.file.FileSystemException: /proc: Too many open files

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?

Upvotes: 2

Views: 12450

Answers (3)

ACV
ACV

Reputation: 10562

This error may happen when you're trying to do some file related operations too often. Usually there is a loop without a delay. Try adding a Thread.sleep().

Upvotes: -1

Vladimir Vagaytsev
Vladimir Vagaytsev

Reputation: 2891

Looks like you have problems in you logic, as Peter mentioned. You have to be sure that you're closing I/O resources at each iteration. Use try-with-resources to handle I/O resources inside your for-loop. Could you show you logic code as well?

Oh, you surely need to close DirectoryStream as well.

Upvotes: 2

maslan
maslan

Reputation: 2178

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();

Upvotes: 3

Related Questions