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

♀尐吖头ヾ 提交于 2019-11-27 22:07:37

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/14893205/how-to-replace-file-listfilesfilefilter-filter-with-nio-in-java-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!