listFiles(FileFilter filter) 的源码解析

简单分析下File.listFiles(FileFilter filter)的内部实现
1.首先我们知道listFiles的作用是返回 File 所有的子文件然后可以传入一个FileFilter过滤器得到相关的过滤后的文件
下面是listFile的源码



    public File[] listFiles(FilenameFilter filter) {
        String ss[] = list();<span style="white-space:pre">			</span>  //先用ss存放所有的子文件的名字
        if (ss == null) return null;<span style="white-space:pre">		</span>  //如果没有子文件那么就返回null
        ArrayList<File> files = new ArrayList<>();//实例化一个容器来存放过滤后的子文件
        for (String s : ss)<span style="white-space:pre">			</span>  //对子文件进行过滤和遍历
            if ((filter == null) || filter.accept(this, s))//accept()传给其两个参数,父文件 和子文件的名字
                files.add(new File(s, this));         //如果过滤器为空或者通过了过滤就把该子文件加入到容器里面
        return files.toArray(new File[files.size()]);//把容器变成数组返回
    }
下面是  FileFilter的源码就是一个接口然后要自己实现accept()方法


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);
}
accept实现方法
 accept(File dir,String name){

return new File(dir,name).isFile() && name.endsWith("png") ;//判断是文件然后以"png"结尾就可以了

}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值