您的位置:首页 > 编程语言 > Java开发

Java 查找指定文件夹下的匹配文件

2016-08-29 11:07 543 查看
转载:http://blog.csdn.net/jdsjlzx/article/details/6993316

项目开发过程中我遇到了这样的问题:获取指定文件夹下的名字为xxx.jpg的文件

直接上代码吧:下面这段代码仅仅是判断文件是否存在,如果存在获取该文件的文件路径。

例如获取cope.jpg的文件,直接把下面代码中的文件名改为String fileName = "cope,jpg"就行了

如果想获取F盘下的Test文件夹下的文件,把下面的查找路径改一下就行了String baseDIR = “F://Test”;(貌似一个/也行这样:F:/Test)

根据适当情况可以对下面的查找语句进行优化:比如查找固定文件test.jpg,已经知道文件夹下就一个该文件,所以在获取到之后直接return结束遍历就行了没必要继续遍历了。

注意:下面的代码并没有处理空文件夹的情况。如果文件夹中没有文件,会报错!自己用的时候加一个判断就行了,可以参考场景优化二

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);
}
}


上面这个是通用的遍历查找匹配。既然是通用的当然各种情况都要考虑,在某些特定的场景下效率会比较慢。

场景优化1:查找特定文件,比如查找test.jpg文件。这样已经知道文件名了。不需要使用通配符匹配了。

下面是优化的代码,返回查找到的文件(根据个人需要也可以改为返回文件路径,这里就不改了)

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 = "F:/KuaiDi";
// 找扩展名为txt的文件
String fileName = "copy.jpg";

File imagFile = findFiles(baseDIR, fileName);
}

/**
* 递归查找文件
* @param baseDirName 查找的文件夹路径
* @param targetFileName 需要查找的文件名
* @param fileList 查找到的文件集合
*/
public static File findFiles(String baseDirName, String targetFileName) {

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);
}else if(tempFile.isFile()){
tempName = tempFile.getName();
if(tempName.equals("copy.jpg")){
System.out.println(tempFile.getAbsoluteFile().toString());
return tempFile.getAbsoluteFile();
}
}
}
return null;
}

}

场景优化二:已经知道遍历的文件夹下只有文件没有子文件夹了,就可以去掉判断是不是文件夹的代码。

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 = "F:/KuaiDi";
// 找扩展名为txt的文件
String fileName = "copy.jpg";

File imagFile = findFiles(baseDIR, fileName);
}

/**
* 递归查找文件
* @param baseDirName 查找的文件夹路径
* @param targetFileName 需要查找的文件名
* @param fileList 查找到的文件集合
*/
public static File findFiles(String baseDirName, String targetFileName) {

File baseDir = new File(baseDirName); // 创建一个File对象
if (!baseDir.exists() || !baseDir.isDirectory()) { // 判断目录是否存在
System.out.println("文件查找失败:" + baseDirName + "不是一个目录!");
}
String tempName = null;

File tempFile;
File[] files = baseDir.listFiles();
if(files.length==0){//该文件夹下没有文件,为空文件夹
System.out.println("为空文件夹");
return null;
}
for (int i = 0; i < files.length; i++) {
tempFile = files[i];
tempName = tempFile.getName();
if(tempName.equals("copy.jpg")){
System.out.println(tempFile.getAbsoluteFile().toString());
return tempFile.getAbsoluteFile();

}
}
return null;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: