【Java基础】FilenameFilter

FilenameFilter用来根据给定文件或者目录的名称进行过滤,和FileFilter功能类似,区别在于两者的形式.

首先,看一下FilenameFilter的定义:

@FunctionalInterface
public interface FilenameFilter {
    /**
     * Tests if a specified file should be included in a file list.
     * 测试给定文件是否加入到文件列表中
     * @param   dir    the directory in which the file was found. 文件所在的目录
     * @param   name   the name of the file. 当前文件的名称
     * @return  <code>true</code> if and only if the name should be
     * included in the file list; <code>false</code> otherwise.
     */
    boolean accept(File dir, String name);
}

开始学习这个接口的时候,觉得dir这个参数没有必要,主要是在学习FileFilter的时候,就没有定义文件所在的目录,定义如下:

@FunctionalInterface
public interface FileFilter {

    /**
     * Tests whether or not the specified abstract pathname should be
     * included in a pathname list.
     * 测试是否需要将给定的抽象路径加入到路径的列表
     *
     * @param  pathname  The abstract pathname to be tested 
     * @return  <code>true</code> if and only if <code>pathname</code>
     *          should be included
     */
    boolean accept(File pathname);
}

后来觉得这两个接口在参数列表的不同,其实是有道理的,首先FileFilter中的pathname是File类型的,其实可以通过pathname.getParent()可以间接的获取到所在的目录,但是对于FilenameFilter接口,如果不显示传递进行,则在接口实现里面需要访问所在目录的时候,则比较繁琐。可能大家会想到,我可以直接new File(pathname).getParent()就可以知道了啊,但是我们这个pathname的获取,应该是通过parentDir.listFiles等方法获取的,这时候,执行环境已经有了parentDir,我们没有必要在去自己显示的去查找了,咳,感觉有点啰嗦了<_<. 这是自己浅薄的理解,如果不正确欢迎朋友指正。

下面我们通过一个简单的示例来了解一下怎么使用该接口, 例子还是过滤出所有的txt文本文件(没有创意。。。)

import java.io.File;

public class FilenameFilterDemo {
    public static void main(String[] args) {
        File currentDir = new File(".");
        String[] fileNames = currentDir.list((file, name) -> name.endsWith(".txt"));
        for(String filename : fileNames) {
            System.out.println(filename);
        }
    }
}

执行结果(个人环境):

b.txt
data.txt
input.txt
nio-output.txt
output.txt
tempt.txt
writesomebytes.txt
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值