Java遞歸搜索指定文件夾下的匹配文件
package com.lzx.file;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class FileDemo07 {
public static void main(String[] args) {
// 在此目錄中找文件
String baseDIR = "d:/temp";
// 找擴展名為txt的文件
String fileName = "*.txt";
List resultList = new ArrayList();
findFiles(baseDIR, fileName,resultList);
if (resultList.size() == 0) {
System.out.println("No File Fount.");
} else {
for (int i = 0; i < resultList.size(); i++) {
System.out.println(resultList.get(i));//顯示查找結果。
}
}
}
/**
* 遞歸查找文件
* @param baseDirName 查找的文件夾路徑
* @param targetFileName 需要查找的文件名
* @param fileList 查找到的文件集合
*/
public static void findFiles(String baseDirName, String targetFileName, List fileList) {
File baseDir = new File(baseDirName); // 創建一個File對象
if (!baseDir.exists() || !baseDir.isDirectory()) { // 判斷目錄是否存在
System.out.println("文件查找失敗:" + baseDirName + "不是一個目錄!");
}
String tempName = null;
//判斷目錄是否存在
File tempFile;
File[] files = baseDir.listFiles();
for (int i = 0; i < files.length; i++) {
tempFile = files[i];
if(tempFile.isDirectory()){
findFiles(tempFile.getAbsolutePath(), targetFileName, fileList);
}else if(tempFile.isFile()){
tempName = tempFile.getName();
if(wildcardMatch(targetFileName, tempName)){
// 匹配成功,將文件名添加到結果集
fileList.add(tempFile.getAbsoluteFile());
}
}
}
}
/**
* 通配符匹配
* @param pattern 通配符模式
* @param str 待匹配的字符串
* @return 匹配成功則返回true,否則返回false
*/
private static boolean wildcardMatch(String pattern, String str) {
int patternLength = pattern.length();
int strLength = str.length();
int strIndex = 0;
char ch;
for (int patternIndex = 0; patternIndex < patternLength; patternIndex++) {
ch = pattern.charAt(patternIndex);
if (ch == '*') {
//通配符星號*表示可以匹配任意多個字符
while (strIndex < strLength) {
if (wildcardMatch(pattern.substring(patternIndex + 1),
str.substring(strIndex))) {
return true;
}
strIndex++;
}
} else if (ch == '?') {
//通配符問號?表示匹配任意一個字符
strIndex++;
if (strIndex > strLength) {
//表示str中已經沒有字符匹配?了。
return false;
}
} else {
if ((strIndex >= strLength) || (ch != str.charAt(strIndex))) {
return false;
}
strIndex++;
}
}
return (strIndex == strLength);
}
}
最後更新:2017-04-02 06:52:09