带参数的listFiles方法支持对于子文件进行过滤,只获取需要满足条件的文件对象
FilenameFilter接口中包含一个accept(File dir,String name)方法,该方法用于对指定File的所有子目录或者文件进 行迭代,如果方法返回true则list方法会获取该目录或者文件
@FunctionalInterface
public interface FilenameFilter {
//参数dir是文件所在的目录,name是文件名称
boolean accept(File dir, String name); //当返回值为true时表示要,否则不要
}
public class Test {
public static void main(String[] args) {
File ff=new File("c:/windows");
File[] children=ff.listFiles(new MyFileNameFilter());
for(File temp:children)
System.out.println(temp.getAbsolutePath());
}
static class MyFileNameFilter implements FilenameFilter{
public boolean accept(File dir, String name) {
return name.endsWith(".exe");
}
}
}
匿名内部类的写法: 推荐写法
public class Test {
public static void main(String[] args) {
File ff=new File("c:/windows");
File[] children=ff.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name!=null && name.endsWith(".exe");
}
});
for(File temp:children)
System.out.println(temp.getAbsolutePath());
}
}