2 回答
TA贡献1847条经验 获得超11个赞
试试这个代码:
// for exlude file extension
NotFileFilter suffixFileFilterFileFilter=new NotFileFilter(new
SuffixFileFilter(new String[] { "txt", "java" }));
//to include only selected extension use below one
//IOFileFilter suffixFileFilterFileFilter= new SuffixFileFilter(new String[] { "java", "txt" });
NotFileFilter directoryFileFilterFileFilter=new NotFileFilter(new
PrefixFileFilter(new String[] { "tolearn", "dir2" })); // for directory
File dir = new File("D:\\SomeDir");
List<File> fileList = (List<File>) FileUtils.listFiles(dir,suffixFileFilterFileFilter,directoryFileFilterFileFilter);
for (File file : fileList) {
System.out.println("file: " + file.getCanonicalPath());
}
TA贡献2019条经验 获得超9个赞
干得好
public static void main(String[] args) throws IOException {
File dir = new File("C:\\Users\\cosmap\\Documents\\travel-expenses");
List<String> excludedDirs = Arrays.asList("src", ".git");
List<String> extensions = Arrays.asList("xml", "yml");
listFiles(dir, excludedDirs, extensions).forEach(System.out::println);
}
public static List<File> listFiles(File currentFile, List<String> excludedDirs, List<String> extensions) {
List<File> out = new ArrayList<>();
File[] files = currentFile.listFiles();
// might be null
if(files == null) {
return out;
}
for (File file : files) {
// add recursively only if is directory and not in the excluded list
if(file.isDirectory() && !excludedDirs.contains(file.getName())) {
out.addAll(listFiles(file, excludedDirs, extensions));
// add if is file and in the allowed extensions list
} else if (file.isFile() && extensions.contains(file.getName().substring(file.getName().lastIndexOf('.') + 1))) {
out.add(file);
}
}
return out;
}
添加回答
举报