应用JAVA实现WINDOWS中的dirs查找实例

    xiaoxiao2024-04-20  7

    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 *注:可以直接运行该程序,不过,你最好把该程序拷到你需要的根目录下执行。 */ public class FileSearch {     String fileName;     String currentPath;     boolean regStr;     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);         }     private boolean doSearch(String path) {         if(path==null)             return false;         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());                         }                     }                 else if (allFile[currentFile].getName().equals(fileName)) {                     System.out.println(allFile[currentFile].getAbsolutePath());                     }                 }             //如果是文件夾就采用遞歸處理             else {                 doSearch(allFile[currentFile].getPath());                 }             }         return true;         }     public static void main(String[] args) {         FileSearch fileSearch = new FileSearch("F*.class");         }     }
    转载请注明原文地址: https://ju.6miu.com/read-1288179.html
    最新回复(0)