Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace File.listFiles(FileFilter filter) with nio in Java 7?

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 ?

like image 928
Paul Taylor Avatar asked Feb 15 '13 10:02

Paul Taylor


1 Answers

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.

like image 55
StarPinkER Avatar answered Oct 17 '22 23:10

StarPinkER