Chinaunix首页 | 论坛 | 博客
  • 博客访问: 468221
  • 博文数量: 1496
  • 博客积分: 79800
  • 博客等级: 大将
  • 技术积分: 9940
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-09 13:22
文章分类

全部博文(1496)

文章存档

2011年(1)

2008年(1495)

我的朋友

分类:

2008-09-09 13:30:05

import java.io.File; 
import java.util.regex.Matcher; 
import java.util.regex.MatchResult; 
import java.util.regex.Pattern; 
import java.util.regex.PatternSyntaxException; 
/**
*利用JAVA实现WINDOWS中的dir/s查找
*这里采用正则达式解决了通配符的问题,但是有一点就是不能够通过命令行传参数
*因为如果你通过命令行传数,JAVA会自动把你的带通过的文件名,换成当前目录匹配的文件名,
*如你在命令行以这样传入:javaFileSearcha*,如果当前目录下有a.jpg,a1.jpg,那么a*
*会被自动换成a.jpg,及a1.jpg,如果在当前目录下有目录,并且子目录中有a2.jpg,那这个就查
*不出来。所有现在只能通过其它的方式调用才行,而不能够通过命令行传参数
*这个可能需要拦截器才能够解决这个问题,不过,这个我不会,如果会的并且有兴趣,可以试试
*作者:blog.csdn.net/fenglibing
*注:可以直接运行该程序,不过,你最好把该程序拷到你需要的根目录下执行。
*/
publicclass FileSearch {
String fileName; 
String currentPath; 
booleanregStr; 
Pattern pattern; 
public FileSearch(String fileName) { 
/*********************用正则表达式解决通配符***************************/
if(fileName.indexOf("*")!=-1 || fileName.indexOf("?")!=-1) {
regStr=true; 
if(fileName.indexOf("?")!=-1) {
fileName=fileName.replace("?",".{0,1}"); 
}
/**********因为正则表式中的'*'和DOS中的功能差不多,所以不换***********/
pattern=Pattern.compile(fileName); 
} 
this.fileName=fileName; 
File f=new File(""); //从当前路径开始查找
currentPath=f.getAbsolutePath(); 
doSearch(currentPath); 
} 
privateboolean doSearch(String path) {
if(path==null)
returnfalse; 
File F = new File(path); 
File[] allFile = F.listFiles(); //取得當前目錄下面的所有文件,將其放在文件數組中
int totalNum = allFile.length; //取得當前文件夾中有多少文件(包括文件夾)
int currentFile = 0; 
for (currentFile = 0; currentFile < totalNum; currentFile++) {
if (!allFile[currentFile].isDirectory()) {
//如果是文件是采用處理文件的方式
if(regStr==true) {
Matcher matcher=pattern.matcher(allFile[currentFile].getName()); 
boolean result=matcher.find(); 
if(result) {
System.out.println(allFile[currentFile].getAbsolutePath()); 
}
}
elseif (allFile[currentFile].getName().equals(fileName)) {
System.out.println(allFile[currentFile].getAbsolutePath()); 
}
}
//如果是文件夾就采用遞歸處理
else {
doSearch(allFile[currentFile].getPath()); 
}
}
returntrue; 
}
publicstaticvoid main(String[] args) {
FileSearch fileSearch = new FileSearch("t?.jpg"); 
}
}

--------------------next---------------------

阅读(36) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~