java如何获取文件下某种类型的文件呢,本文通过递归筛选实现此功能,代码如下:
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
*
* @author yaohucaizi
*/
public class FileViewer {
/**
* 读取文件夹下所以文件
*
* @param dirPath
* @param fileTypes
* @return
*/
public static List<String> getAllFilePathByDir_FilterByFileType(String dirPath,
List<String> fileTypes) {
String localClassFilePath = FileViewer.class.getResource("/").getPath();
String contextFilePath = localClassFilePath.substring(1, localClassFilePath.length() - 16);
contextFilePath = contextFilePath.replace("/", "\\");
List<String> filePathList = new ArrayList<String>();
for (int index = 0; index < fileTypes.size(); index++) {
fileList = new ArrayList<String>();
List arrayList = FileViewer.getListFiles(dirPath, fileTypes.get(index), true);
if (arrayList.isEmpty()) {
System.out.println("没有符号要求的文件");
} else {
for (Iterator i = arrayList.iterator(); i.hasNext();) {
String temp = (String) i.next();
temp = temp.replace(contextFilePath, "");//把根路径去掉
System.out.println(temp);
filePathList.add(temp);
}
}
}
for (int replaceIndex = 0; replaceIndex < filePathList.size(); replaceIndex++) {
filePathList.set(replaceIndex, filePathList.get(replaceIndex).replace("\\", "/"));
}
return filePathList;
}
public static List<String> fileList = new ArrayList<String>();
/**
* 添加文件后缀名称
*
* @return
*/
public static List<String> suffixlist() {
List<String> list = new ArrayList<String>();
list.add("html");
list.add("htm");
return list;
}
/**
*
* @param path 文件路径
* @param suffix 后缀名
* @param isdepth 是否遍历子目录
* @return
*/
public static List getListFiles(String path, String suffix, boolean isdepth) {
File file = new File(path);
return FileViewer.listFile(file, suffix, isdepth);
}
public static List listFile(File f, String suffix, boolean isdepth) {
// 是目录,同时需要遍历子目录
if (f.isDirectory() && isdepth == true) {
File[] t = f.listFiles();
for (int i = 0; i < t.length; i++) {
listFile(t[i], suffix, isdepth);
}
} else {
String filePath = f.getAbsolutePath();
if (suffix != null) {
int begIndex = filePath.lastIndexOf(".");// 最后一个.(即后缀名前面的.)的索引
String tempsuffix = "";
if (begIndex != -1)// 防止是文件但却没有后缀名结束的文件
{
tempsuffix = filePath.substring(begIndex + 1, filePath
.length());
}
if (tempsuffix.equals(suffix)) {
fileList.add(filePath);
}
} else {
// 后缀名为null则为所有文件
fileList.add(filePath);
}
}
return fileList;
}
public static void main(String[] args) {
List<String> listResult = getAllFilePathByDir_FilterByFileType("D:\\netbeans workspace\\EDMProject\\trunk\\target\\EDMProject-1.0-SNAPSHOT\\upload\\template/1368683270902", suffixlist());
System.out.println(listResult.size() + "\t" + listResult.get(0));
}
}