import java.io.*;
import java.util.*;
public class DirList3 {
public static void main(String[] args) {
File path = new File(".");
//存放文件名数组的list
ArrayList<String> fStr = new ArrayList<String>();
//存放目录的List
ArrayList<File> fls = new ArrayList<File>();
//文件过滤器,主要是列出指定目录下的所有文件包括其子目录下的所有文件,并列出符合表达式的文件名
FileFilter ff = new FileFilter(args[0]);
//列出所有目录,并将其添加到fls中
ff.listAllDir(path, fls);
File f = null;
String[] list = null;
for(Iterator<File> iter = fls.iterator(); iter.hasNext(); ) {
f = iter.next();
list = f.list(ff);
if(list.length != 0)
fStr.addAll(Arrays.asList(list));
}
//列出所有符合的文件名
System.out.println(Arrays.toString(fStr.toArray(new String[fStr.size()]))); }
}
FileFilter类
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.regex.Pattern;
public class FileFilter implements FilenameFilter {
private Pattern pattern;
public FileFilter(String regex) {
pattern = Pattern.compile(regex);
}
public boolean accept(File dir, String name) {
// TODO Auto-generated method stub
return pattern.matcher(name).matches();
}
public void listAllDir(File dir, ArrayList<File> fls) {
File[] fs = dir.listFiles();
for(File item:fs) {
if(item.isDirectory()) {
fls.add(item);
listAllDir(item, fls);
}
}
fls.add(dir);
}
} |