Java文件操作:文件夹中搜索文件
生活随笔
收集整理的這篇文章主要介紹了
Java文件操作:文件夹中搜索文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在文件夾中搜索文件,找到的話將文件的絕對路徑列表返回
/*** 遞歸查找文件* @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.getAbsolutePath());}}}}/*** 通配符匹配* @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);}總結
以上是生活随笔為你收集整理的Java文件操作:文件夹中搜索文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Dubbo—dubbo admin安装
- 下一篇: Java调用js方法