FileFilter接口
public interface FileFilter { /** * Tests whether or not the specified abstract pathname should be * included in a pathname list. * * @param pathname The abstract pathname to be tested * @return <code>true</code> if and only if <code>pathname</code> * should be included */ boolean accept(File pathname); }
当我们调用listFiles()方法时,支持传入一个FileFilter接口实现类,对获取的文件进行过滤,只有满足条件的文件才会返回。
//实例化FileFilter,并重写accept接口 FileFilter fileFilter = new FileFilter() { @Override public boolean accept(File pathname) { //如果文件名称后缀为docx,就把该文件返回,反之则不返回 if (pathname.getName().endsWith("docx")) { return true; } return false; } }; File[] listFiles = dir.listFiles(fileFilter); for (File file : listFiles) { System.out.println(file.getName()); }

浙公网安备 33010602011771号