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

问题描述

我有一些用Java 6编写的文件I/0遍历代码,试图将其移动为Java 7中的New 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中File Path可以替代多少?

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

推荐答案

使用 Files#newDirectoryStream DirectoryStream.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)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 02:59