简单分析下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"结尾就可以了
}
原文:https://blog.csdn.net/yxs9527/article/details/51283646