import java.io.File;
import java.io.FilenameFilter;
import java.util.regex.Pattern;
/*
* TIJ4 书上的一个类,拿来直接用了
*/
public class DirList {
static File path = new File("."); //默认是当前文件目录
static String regex = ".*//.xls"; //默认的查找的文件格式
public static FilenameFilter filter(final String regex){
return new FilenameFilter() //匿名内部类
{
private Pattern pattern = Pattern.compile(regex);
//回掉函数 具体的过程还不清楚
public boolean accept(File dir,String name){
return pattern.matcher(name).matches();
}
};
}
DirList(){};
DirList(File file, String reg){
path = file;
regex = reg;
}
void setPath(File f){ path = f;}
void setRegex(String reg) {regex = reg;}
String[] dirList(){
String[] files ;
files = path.list(filter(regex));
return files;
}
public static void main(String[] args) {
DirList dl = new DirList(); //先在当前目录下找
String[] tmp = dl.dirList();
for(String s :tmp)
System.out.println(s);
System.out.println("-------------------------------");
dl.setPath(new File("c://user")); //重新 设置目录
dl.setRegex(".*//.xls"); //重新 设置查找条件
tmp = dl.dirList();
for(String s :tmp)
System.out.println(s);
}
}