一段非常简单的java代码,写成了一个小util :
package com.util;
import java.io.File;
import java.io.FileFilter;
import java.util.List;
public class FileUtil {
/**
* provide two default file filters
*/
public static FileFilter DEFAULT_JSP_FILTER = new JSPFileFilter();
public static FileFilter DEFAULT_TXT_FILTER = new TXTFileFilter();
/**
* This method will get all the target files under a specific directory
*
* @param targetDir
* @param filter
* @param resultFiles
* @return
*/
public static List<File> filterTargetFiles(File targetDir,
FileFilter filter, List<File> resultFiles) {
/**
* listFiles : only list the files in the current directory, not include
* the files in the sub directories.
*/
File[] files = targetDir.listFiles(filter);
for (File file : files) {
if (file.isDirectory()) {
filterTargetFiles(file, filter, resultFiles);
} else {
resultFiles.add(file);
}
}
return resultFiles;
}
private static class JSPFileFilter implements FileFilter {
@Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
String fileName = file.getName();
return fileName.matches("(?i).+jsp$");
}
}
private static class TXTFileFilter implements FileFilter {
@Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
String fileName = file.getName();
return fileName.matches("(?i).+txt$");
}
}
}
测试代码 :
package com.salmon;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.util.FileUtil;
public class TestReadFiles {
public static void main(String[] args) {
String targetDirPath = "D:\\ZZZZTestDir";
File targetDir = new File(targetDirPath);
List<File> allFiles = new ArrayList<File>();
allFiles = FileUtil.filterTargetFiles(targetDir, FileUtil.DEFAULT_TXT_FILTER, allFiles);
// after get all the files, do the specific logic for the target files
doTheLogic(allFiles);
}
/**
* Get all the files in the target directory, here we could conduct any logic for the files
*
* @param filesList
*/
private static void doTheLogic(List<File> filesList){
for(File file : filesList){
System.out.println(file.getPath());
}
}
}