Java递归搜索指定文件夹下的匹配文件

本文介绍了一个使用Java实现的递归文件搜索算法,用于查找指定目录下所有子文件夹及文件,并筛选出特定文件名的文件。通过自定义通配符匹配功能,实现了灵活的文件查找。实例演示了如何在给定目录中搜索扩展名为.txt的文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文:http://lenj.blog.163.com/blog/static/127420388201081642741448/

importjava.io.File;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.Queue;

/**
*@authortiwson2010-06-02
*
*/
publicclassFileSearcher{

/**
*递归查找文件
*@parambaseDirName查找的文件夹路径
*@paramtargetFileName需要查找的文件名
*@paramfileList查找到的文件集合
*/
publicstaticvoidfindFiles(StringbaseDirName,StringtargetFileName,ListfileList){
/**
*算法简述:
*从某个给定的需查找的文件夹出发,搜索该文件夹的所有子文件夹及文件,
*若为文件,则进行匹配,匹配成功则加入结果集,若为子文件夹,则进队列。
*队列不空,重复上述操作,队列为空,程序结束,返回结果。
*/
StringtempName=null;
//判断目录是否存在
FilebaseDir=newFile(baseDirName);
if(!baseDir.exists()||!baseDir.isDirectory()){
System.out.println("文件查找失败:"+baseDirName+"不是一个目录!");
}else{
String[]filelist=baseDir.list();
for(inti=0;i<filelist.length;i++){
Filereadfile=newFile(baseDirName+"\\"+filelist[i]);
//System.out.println(readfile.getName());
if(!readfile.isDirectory()){
tempName=readfile.getName();
if(FileSearcher.wildcardMatch(targetFileName,tempName)){
//匹配成功,将文件名添加到结果集
fileList.add(readfile.getAbsoluteFile());
}
}elseif(readfile.isDirectory()){
findFiles(baseDirName+"\\"+filelist[i],targetFileName,fileList);
}
}
}
}

/**
*通配符匹配
*@parampattern通配符模式
*@paramstr待匹配的字符串
*@return匹配成功则返回true,否则返回false
*/
privatestaticbooleanwildcardMatch(Stringpattern,Stringstr){
intpatternLength=pattern.length();
intstrLength=str.length();
intstrIndex=0;
charch;
for(intpatternIndex=0;patternIndex<patternLength;patternIndex++){
ch=pattern.charAt(patternIndex);
if(ch=='*'){
//通配符星号*表示可以匹配任意多个字符
while(strIndex<strLength){
if(wildcardMatch(pattern.substring(patternIndex+1),
str.substring(strIndex))){
returntrue;
}
strIndex++;
}
}elseif(ch=='?'){
//通配符问号?表示匹配任意一个字符
strIndex++;
if(strIndex>strLength){
//表示str中已经没有字符匹配?了。
returnfalse;
}
}else{
if((strIndex>=strLength)||(ch!=str.charAt(strIndex))){
returnfalse;
}
strIndex++;
}
}
return(strIndex==strLength);
}

publicstaticvoidmain(String[]paramert){
//在此目录中找文件
StringbaseDIR="d:/file";
//找扩展名为txt的文件
StringfileName="*.txt";
ListresultList=newArrayList();
FileSearcher.findFiles(baseDIR,fileName,resultList);
if(resultList.size()==0){
System.out.println("NoFileFount.");
}else{
for(inti=0;i<resultList.size();i++){
System.out.println(resultList.get(i));//显示查找结果。
}
}
}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值