Java.io.FilenameFilter是文件名过滤器,用来过滤不符合规格的文件名,并返回合格的文件;
实例1,匹配指定字符结尾的文件
package cn.test; import java.io.File; import java.io.FilenameFilter; import org.junit.Test; public class Demo4 { @Test public void test1(){ File file = new File("D:/Temp"); FilterBysuffix filter = new FilterBysuffix(".txt"); String[] files = file.list(filter); for (String fileName : files){ System.out.println(fileName); } } } class FilterBysuffix implements FilenameFilter{ private String suffix; public FilterBysuffix(String suffix){ this.suffix=suffix; } @Override public boolean accept(File dir, String name) { return name.endsWith(suffix); } }
结果:
实例2,正则匹配文件
public class Test1 { @Test public void demo1() throws IOException{ File file = new File("D:/tmp"); FilterByMatches filterByMatches = new FilterByMatches(".*txt$"); String[] files = file.list(filterByMatches); for(String f : files){ System.out.println(f); } } } class FilterByMatches implements FilenameFilter{ private String suffix; public FilterByMatches(String suffix){ this.suffix=suffix; } public boolean accept(File dir, String name) { return name.matches(suffix); } }
结果: