Java 遍历指定文件夹及子文件夹下的文件

时间:2023-03-08 21:41:30
Java 遍历指定文件夹及子文件夹下的文件

Java 遍历指定文件夹及子文件夹下的文件

/**
* 遍历指定文件夹及子文件夹下的文件
*
* @author testcs_dn
* @date 2014年12月12日下午2:33:49
* @param file 要遍历的指定文件夹
* @param collector 符合条件的结果加入到此List<File>中
* @param pathInclude 路径中包括指定的字符串
* @param fileNameInclude 文件名称(不包括扩展名)中包括指定的字符串
* @param extnEquals 文件扩展名为指定字符串
* @throws IOException
*/
public static void listFiles(File file,List<File> collector, String pathInclude, String fileNameInclude, String extnEquals) throws IOException {
if (file.isFile()
&& (StringUtils.isBlank(pathInclude) || file.getAbsolutePath().indexOf(pathInclude) != -1)
&& (StringUtils.isBlank(fileNameInclude) || file.getName().indexOf(fileNameInclude) != -1)
&& (StringUtils.isBlank(extnEquals) || file.getName().endsWith(extnEquals))
){
collector.add(file);
}
if((!file.isHidden() && file.isDirectory()) && !isIgnoreFile(file)) {
File[] subFiles = file.listFiles();
for(int i = 0; i < subFiles.length; i++) {
listFiles(subFiles[i],collector, pathInclude, fileNameInclude, extnEquals);
}
}
}

推断文件夹是否须要忽略

	private static boolean isIgnoreFile(File file) {
List<String> ignoreList = new ArrayList<String>();
ignoreList.add(".svn");
ignoreList.add("CVS");
ignoreList.add(".cvsignore");
ignoreList.add("SCCS");
ignoreList.add("vssver.scc");
ignoreList.add(".DS_Store");
for(int i = 0; i < ignoreList.size(); i++) {
if(file.getName().equals(ignoreList.get(i))) {
return true;
}
}
return false;
}