前言
Java实现,通过关键词 在指定的目录及指定目录的所有下级目录,找到文件名相匹配的文件
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.List;
public class CheckFileByKeyword { static int countFiles = 0; static int countFolders = 0; public static File[] searchFile(File folder, final String keyWord) { File[] subFolders = folder.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { if (pathname.isFile()){ countFiles++; }else { countFolders++; } if (pathname.isDirectory()|| (pathname.isFile() && pathname.getName().toLowerCase().contains(keyWord.toLowerCase()))){ return true; }else { return false; } } }); List<File> result = new ArrayList<File>(); for (int i = 0; i < subFolders.length; i++) { if (subFolders[i].isFile()) { result.add(subFolders[i]); } else { File[] foldResult = searchFile(subFolders[i], keyWord); for (int j = 0; j < foldResult.length; j++) { result.add(foldResult[j]); } } } File files[] = new File[result.size()]; result.toArray(files); return files; } public static void main(String[] args) { File folder = new File("D:/Test"); String keyword = "1号文件"; if (!folder.exists()) { System.out.println("目录不存在:" + folder.getAbsolutePath()); return; } File[] result = searchFile(folder, keyword); System.out.println("在 " + folder + " 以及所有子文件时查找对象" + keyword); System.out.println("查找了" + countFiles + " 个文件," + countFolders + " 个文件夹,共找到 " + result.length + " 个符合条件的文件:"); for (int i = 0; i < result.length; i++) { File file = result[i]; System.out.println(file.getAbsolutePath() + " "); } } }
|