如何在 Java 7 中用 nio 替换 File.listFiles(FileFilter filter)? [英] How to replace File.listFiles(FileFilter filter) with nio in Java 7?

查看:32
本文介绍了如何在 Java 7 中用 nio 替换 File.listFiles(FileFilter filter)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些用 Java 6 编写的文件 I/0 遍历代码,试图将它移动到 Java 7 中的新 I/O,但我找不到任何替代这种东西的东西.

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

也就是说,没有办法只过滤路径文件,它返回文件列表,所以如果我想限制在它调用的方法中使用 File,我必须将每个文件转换为路径(file.toPath)看起来比较费力.

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.

我确实看过 FileVisitor 但这似乎不允许您控制树的遍历方式,因此我认为它对我有用.

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.

那么 Java 7 中的 Path for File 有多少替代品?

So how much of a replacement is Path for File in Java 7 ?

推荐答案

使用 Files#newDirectoryStreamDirectoryStream.Filter

代码如下:

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.

这篇关于如何在 Java 7 中用 nio 替换 File.listFiles(FileFilter filter)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆