score:2

Accepted answer

i ran into the same issue (on windows server 2012 r2) when i didn't close the stream. all the files i iterated over were open in read mode until the jvm was shut down. however, it did not occur on mac os x and since the stream depends on os-dependent implementations of filesystemprovider and directorystream, i assume the issue can be os-dependent, too.

contrary to the @ian mclaird comment, it is mentioned in the files.list() documentation that

if timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed.

the returned stream is a directorystream, whose javadoc says:

a directorystream is opened upon creation and is closed by invoking the close method. closing a directory stream releases any resources associated with the stream. failure to close the stream may result in a resource leak.

my solution was to follow the advice and use the try-with-resources construct

try (stream<path> filelisting = files.list(directorypath)) {
    // use the filelisting stream
}

when i closed the stream properly (used the above try-with-resources construct), the file handles were immediately released.

if you don't care about getting the files as a stream or you are ok with loading the whole file list into memory and convert it to a stream yourself, you can use the io api:

file directory = new file("/path/to/dir");
file[] files = directory.listfiles();
if (files != null) { // 'files' can be null if 'directory' "does not denote a directory, or if an i/o error occurs."
    // use the 'files' array or convert to a stream:
    stream<file> filestream = arrays.stream(files);
}

i did not experience any file-locking issues with this one. however, note that both solutions rely on native, os-dependent code, so i advise testing in all environments you would be using.

score:1

you may use the apache fileutils library, which use the old java.io.file.listfiles function internaly :

iterator<file> it = fileutils.iteratefiles(folder, null, true);
while (it.hasnext())
{
   file fileentry = (file) it.next();
}

score:4

if that happens why not to use old school java.io.file?

file folder = new file(pathtofolder);
string[] files = folder.list();

tested with lsof and it looks like no of the listed files is open. you can convert the array to a list or stream afterwards. unless the directory is too large or remote, then i would try to blame path objects and garbage-collect or somehow destroy them.


Related Query

More Query from same tag