使用 apache commons fileutils 排除特定的子目录 [英] Exclude specific sub-directories using apache commons fileutils
问题描述
我想列出当前目录下的所有文件,但不包括使用 apache commons lib 的子目录及其子目录中的所有文件.
例如:如果我的当前目录是--A,其子目录为B、C、D
B 的子目录为 b1,b2(b1 的子目录为 b12),C 的子目录为 c1,c2...现在我想列出 C,c1,c2, D 中的所有文件(不包括 B , b1 ,b12 , b2 )
任何帮助将不胜感激!
使用 org.apache.commons.io.FileFilter,有一个 很好的例子,说明如何在 JavaDoc 中使用它.>
例如我有一个目录结构,如:
/tmp/testFilter/A/tmp/testFilter/B/tmp/testFilter/C/c1/tmp/testFilter/C/c2/tmp/testFilter/D/d1
然后我可以使用以下代码仅列出 C 和 D 下的文件:
公共类 FileLister {公共静态无效主(字符串参数[]){File dir = new File("/tmp/testFilter");String[] 文件 = dir.list(新的 NotFileFilter(新的 OrFileFilter(新前缀文件过滤器(A"),新前缀文件过滤器(B"))));列表文件(目录,文件);}private static void listFiles(File rootDir, String[] files) {对于(字符串文件名:文件){File fileOrDir = new File(rootDir, fileName);如果 (fileOrDir.isDirectory()) {listFiles(fileOrDir, fileOrDir.list());} 别的 {System.out.println(fileOrDir);}}}}
I want to list all the files under current directory but excluding all the files within the subdirectory and it's subdirectories using apache commons lib.
For Example : If my current directory is -- A and its subdirectory as B, C ,D
B having subdirectory as b1,b2 (b1 has b12 as its subdirectory) and C having c1 , c2...
now I want to list all the files in C,c1,c2, D (excluding B , b1 ,b12 , b2 )
Any help will be highly appreciated!
Use org.apache.commons.io.FileFilter, there's a good example of how to use it in the JavaDoc.
For example I have a directory structure like:
/tmp/testFilter/A
/tmp/testFilter/B
/tmp/testFilter/C/c1
/tmp/testFilter/C/c2
/tmp/testFilter/D/d1
Then I could list only the files under C and D with the following code:
public class FileLister {
public static void main(String args[]) {
File dir = new File("/tmp/testFilter");
String[] files = dir.list(
new NotFileFilter(
new OrFileFilter(
new PrefixFileFilter("A"),
new PrefixFileFilter("B")
)
)
);
listFiles(dir, files);
}
private static void listFiles(File rootDir, String[] files) {
for (String fileName: files) {
File fileOrDir = new File(rootDir, fileName);
if (fileOrDir.isDirectory()) {
listFiles(fileOrDir, fileOrDir.list());
} else {
System.out.println(fileOrDir);
}
}
}
}
这篇关于使用 apache commons fileutils 排除特定的子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!