我需要列出除几个子目录之外的目录中的文件(指定扩展名)。
我可以使用扩展程序进行过滤,但不能同时使用两个条件 1)文件应按扩展名过滤 2)应该排除几个子目录
File dir = new File("D:\\SomeDir");
String[] extensions = new String[] { "txt", "java" };
List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true);
for (File file : files) {
System.out.println("file: " + file.getCanonicalPath());
}
如何排除选定的子目录?
答案 0 :(得分:1)
你在这里
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;
}
答案 1 :(得分:1)
尝试以下代码:
// 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());
}
答案 2 :(得分:0)
您可以使用FileUtils.listFilesAndDirs
或其他解决方案:
除了列出所有目录并排除一些目录,您还可以排除第3行List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, *false*);
中的子目录,并在第二个循环中包含要列出文件的子目录。