《Thinking in Java》Chapter 18
原创
©著作权归作者所有:来自51CTO博客作者说文科技的原创作品,请联系作者获取转载授权,否则将追究法律责任
《Thinking in Java》Chapter 18
1. 目录列表器
package chapter18;
import java.io.File;
import java.io.FilenameFilter;
import java.util.regex.Pattern;
public class Main {
private static String fileName = "D:\\Java_Project\\DayProgram\\studyJava";
public static void main(String[] args) {
listFile();
listMatchFile(".*.iml",fileName);//过滤的条件是: .iml结束的文件。注意这个regex的表述
}
public static void listFile(){
System.out.println(fileName+" 下的文件(夹)有:");
File file = new File(fileName);
String fileList [] = file.list();
for (String str : fileList) {
System.out.println("file name is: "+str );
//System.out.println("file is a directory:" + );
}
}
public static void listMatchFile(String regex,String dir){
System.out.println("\n\n匹配的文件有:");
File file = new File(dir);
String res [] = file.list(new Filter(regex));
for(String str : res)
System.out.println(str);
}
public static class Filter implements FilenameFilter {
private Pattern pattern;
public Filter(String regex){
pattern = Pattern.compile(regex);
}
public boolean accept(File dir, String name) {
return pattern.matcher(name).matches();
}
}
}
1.2 运行结果
1.3 注意事项
2.