歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java遞歸搜索指定文件夾下的匹配文件

Java遞歸搜索指定文件夾下的匹配文件

日期:2017/3/1 10:55:48   编辑:Linux編程
Java遞歸搜索指定文件夾下的匹配文件
  1. package com.lzx.file;
  2. import java.io.File;
  3. import java.util.ArrayList;
  4. import java.util.LinkedList;
  5. import java.util.List;
  6. public class FileDemo07 {
  7. public static void main(String[] args) {
  8. // 在此目錄中找文件
  9. String baseDIR = "d:/temp";
  10. // 找擴展名為txt的文件
  11. String fileName = "*.txt";
  12. List resultList = new ArrayList();
  13. findFiles(baseDIR, fileName,resultList);
  14. if (resultList.size() == 0) {
  15. System.out.println("No File Fount.");
  16. } else {
  17. for (int i = 0; i < resultList.size(); i++) {
  18. System.out.println(resultList.get(i));//顯示查找結果。
  19. }
  20. }
  21. }
  22. /**
  23. * 遞歸查找文件
  24. * @param baseDirName 查找的文件夾路徑
  25. * @param targetFileName 需要查找的文件名
  26. * @param fileList 查找到的文件集合
  27. */
  28. public static void findFiles(String baseDirName, String targetFileName, List fileList) {
  29. File baseDir = new File(baseDirName); // 創建一個File對象
  30. if (!baseDir.exists() || !baseDir.isDirectory()) { // 判斷目錄是否存在
  31. System.out.println("文件查找失敗:" + baseDirName + "不是一個目錄!");
  32. }
  33. String tempName = null;
  34. //判斷目錄是否存在
  35. File tempFile;
  36. File[] files = baseDir.listFiles();
  37. for (int i = 0; i < files.length; i++) {
  38. tempFile = files[i];
  39. if(tempFile.isDirectory()){
  40. findFiles(tempFile.getAbsolutePath(), targetFileName, fileList);
  41. }else if(tempFile.isFile()){
  42. tempName = tempFile.getName();
  43. if(wildcardMatch(targetFileName, tempName)){
  44. // 匹配成功,將文件名添加到結果集
  45. fileList.add(tempFile.getAbsoluteFile());
  46. }
  47. }
  48. }
  49. }
  50. /**
  51. * 通配符匹配
  52. * @param pattern 通配符模式
  53. * @param str 待匹配的字符串
  54. * @return 匹配成功則返回true,否則返回false
  55. */
  56. private static boolean wildcardMatch(String pattern, String str) {
  57. int patternLength = pattern.length();
  58. int strLength = str.length();
  59. int strIndex = 0;
  60. char ch;
  61. for (int patternIndex = 0; patternIndex < patternLength; patternIndex++) {
  62. ch = pattern.charAt(patternIndex);
  63. if (ch == '*') {
  64. //通配符星號*表示可以匹配任意多個字符
  65. while (strIndex < strLength) {
  66. if (wildcardMatch(pattern.substring(patternIndex + 1),
  67. str.substring(strIndex))) {
  68. return true;
  69. }
  70. strIndex++;
  71. }
  72. } else if (ch == '?') {
  73. //通配符問號?表示匹配任意一個字符
  74. strIndex++;
  75. if (strIndex > strLength) {
  76. //表示str中已經沒有字符匹配?了。
  77. return false;
  78. }
  79. } else {
  80. if ((strIndex >= strLength) || (ch != str.charAt(strIndex))) {
  81. return false;
  82. }
  83. strIndex++;
  84. }
  85. }
  86. return (strIndex == strLength);
  87. }
  88. }
Copyright © Linux教程網 All Rights Reserved