疑问与错误:
1、你所用的FileFilterByName类,我未查找到,请问是自己写的吗?
2、File[] file = f.listFiles(new FileFilterByName(".txt"));这句代码会让后面遍历时,子目录也会被排除在外,因为子目录的后缀不是“.txt”;
这是我实现相同功能的代码,请参考:- import java.io.File;
- import java.io.FileFilter;
- class Test
- {
- public static void main(String[] args)
- {
- File file=new File("C:\\Test");
- FileFilter filter=new FileFilter(){
- @Override
- public boolean accept(File pathname) {
- return pathname.getName().endsWith(".txt");
- }
- };
- listAll(file,filter,0);
- }
- public static void listAll(File dir,FileFilter filter,int level) {
- System.out.println(getLevel(level)+dir.getName());
- level++;
- File[] files = dir.listFiles();
- for (File file : files) {
- if(file.isDirectory())
- listAll(file,filter,level);
- else{
- if(filter.accept(file))
- System.out.println(getLevel(level)+file.getName());
- }
- }
- }
- private static String getLevel(int level) {
- StringBuilder sb=new StringBuilder("|--");
- for (int i = 0; i < level; i++) {
- sb.insert(0," ");
- }
- return sb.toString();
- }
- }
复制代码
|