从给定的一个路径中筛选中某种格式的文件,通常的做法,便是遍历该目录,然后按照文件后缀来判断该文件是否符合判断条件。
public class FileFilter { public static void main(String[] args) { File filepath = new File("F:\\论文\\中国知网论文\\中国知网论文"); List<File> list = filterFile(filepath); System.out.println(list.size()); } public static List<File> filterFile(File file) { List<File> list = new ArrayList<File>(); File[] fileList = file.listFiles(); for (int i = 0; i < fileList.length; i++) { // 判断该file是否是目录,是目录,则继续深入遍历 if (fileList[i].isDirectory()) { filterFile(fileList[i]); // 是文件时,判断后缀是否是PDF结尾,是则截取出来该文件 } else if (fileList[i].getName().endsWith(".pdf")) { list.add(fileList[i]); } else continue; } return list; } }
其实 java的File 类有一个自带的过滤方法,即FilenameFilter接口
FilenameFilter接口自带一个accept方法,过滤符合条件的文件类型
package java.io; /** * Instances of classes that implement this interface are used to * filter filenames. These instances are used to filter directory * listings in the <code>list</code> method of class * <code>File</code>, and by the Abstract Window Toolkit's file * dialog component. * * @author Arthur van Hoff * @author Jonathan Payne * @see java.awt.FileDialog#setFilenameFilter(java.io.FilenameFilter) * @see java.io.File * @see java.io.File#list(java.io.FilenameFilter) * @since JDK1.0 */ 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); }
FilenameFilter 接口中的accept方法,主要判断给定的文件是否包含在该目录中
通过FilenameFilter 接口改造后的代码
public class FileFilter { public static void main(String[] args) { File filepath = new File("F:\\论文\\中国知网论文\\中国知网论文"); List<File> list = filterFile(filepath); System.out.println(list.size()); } public static List<File> filterFile(File file) { // 定义变量list来接收最后的文件列表 List<File> list = new ArrayList<File>(); // 将文件类型给到FilterName 中 FilterName filter = new FilterName(".abcd"); // 文件过滤 String[] files = file.list(filter); // 由于File.list(FilenameFilter filter) 返回结果为数组 // 此处将数组转换为list if (null != files) { for (String fileName : files) { list.add(new File(fileName)); } } return list; } } class FilterName implements FilenameFilter { private String type; // 构造方法,定义要过滤的文件类型 FilterName(String type) { this.type = type; } @Override public boolean accept(File dir, String name) { return name.endsWith(type); } }
时间: 2024-10-05 02:54:40