File类的两种过滤器接口:
FilenameFilter:需要实现的方法boolean accept(File dir, String name);
FileFilter:需要实现的方法boolean accept(File pathname);
过滤器的使用方法:首先创建过滤器实例,然后在File类的list()和listFiles()中使用过滤器实例作为参数。
1.创建过滤器的实例
实现FilenameFilter接口的过滤器实例
public class FilterByName implements FilenameFilter{
private String sufix;
public FilterByName(String sufix){
this.sufix = sufix;
}
@Override
public boolean accept(File dir, String name) {
if(name.endsWith(sufix)) return true;
else return false;
}
}
实现FileFilter接口的过滤器实例
public class FilterByPath implements FileFilter {
private String sufixName;
public FilterByPath(String sufixName){
this.sufixName = sufixName;
}
@Override
public boolean accept(File pathname) {
String name = pathname.getName();
if(name.endsWith(sufixName)) return true;
else return false;
}
}
2.使用场景,在某个目录下过滤出后缀为".exe"的文件。
第一种方法:File[] listFiles(FileFilter filter);
@Test
public void testCase1(){
File file = new File("E:\\learn_materials\\资料");
FilterByPath fbp = new FilterByPath(".exe");
File[] arr = file.listFiles(fbp);
System.out.println(arr.length);
for(File f:arr){
System.out.println(f);
}
}
第二种:File[] listFiles(FilenameFilter filter)
@Test
public void testCase2(){
File file = new File("E:\\learn_materials\\资料");
FilterByName fbn = new FilterByName(".exe");
File[] arr = file.listFiles(fbn);
System.out.println(arr.length);
for(File f:arr){
System.out.println(f);
}
}
第一种和第二种方法的过滤结果:
6
E:\learn_materials\资料\BadboyInstaller-2.2.5.exe
E:\learn_materials\资料\eclipse-inst-win64.exe
E:\learn_materials\资料\Fiddler_5.0.20173.49666_Setup.exe
E:\learn_materials\资料\Firefox Setup 36.0.exe
E:\learn_materials\资料\jdk-8u151-windows-x64.exe
E:\learn_materials\资料\MySQL-Front_Setup.exe
第三种:String[] list(FilenameFilter filter)
@Test
public void testCase3(){
File file = new File("E:\\learn_materials\\资料");
FilterByName fbn = new FilterByName(".exe");
String[] arr = file.list(fbn);
System.out.println(arr.length);
for(String f:arr){
System.out.println(f);
}
}
第三种方法的过滤结果:
6
BadboyInstaller-2.2.5.exe
eclipse-inst-win64.exe
Fiddler_5.0.20173.49666_Setup.exe
Firefox Setup 36.0.exe
jdk-8u151-windows-x64.exe
MySQL-Front_Setup.exe
listFiles()方法可以使用FilenameFilter和FileFilter过滤器,list()方法只能使用FilenameFilter过滤器。