How to replace File.listFiles(FileFilter filter) with nio in Java 7?
file, java, java-7, nio2, path
Solution
Using Files#newDirectoryStream and DirectoryStream.Filter
Here is the code:
DirectoryStream<Path> stream = Files.newDirectoryStream(dir, new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path entry) throws IOException
{
return Files.isDirectory(entry);
}
});
for (Path entry: stream) {
...
}
BTW, I omitted the exception handling in the above code for simplicity.
Problem
I have some file I/0 traversal code written in Java 6, trying to move it the New I/O in Java 7 but I cannot find any replacement for this kind of stuff. ``` File[] files = dir.listFiles(AudioFileFilter.getInstance()); ``` Namely, no way to filter paths only files, and it returns list of files so I would then have to convert each file to path (file.toPath) if I wanted to limit the use of File in methods it calls, which seems rather laborious. I did look at FileVisitor but this does not seem to allow you to control how the the tree is traversed so I don' think it will work for me. So how much of a replacement is Path for File in Java 7 ?