目錄列示器
本實例演示如何得到一個目錄下的所有文件列表 .
1.?????? 這里利用了 DirFilter 實現(xiàn)了 FilenameFilter 接口 , 因此必須繼承 accept 的方法 .
2.?????? 用到了匹配字符序列與正則表達式指定模式的類 Matcher,Pattern 所以要 java.util.regex 引入 .
實例程序
:
package javaio;
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class DirList {
? public static void main(String[] args) {
? ??File path = new File("c:/");
??? String[] list;
??? if(args.length == 0){
????? list = path.list();
??? }
??? else{
????? // 這里將輸入的參數(shù)作為過濾因子
????? list = path.list(new DirFilter(args[0]));
??? }
??? for(int i = 0; i < list.length; i++){
????? System.out.println(list[i]);
??? }
? }
}
class DirFilter implements FilenameFilter {
?
private Pattern pattern;
? public DirFilter(String regex) {
??? pattern = Pattern.compile(regex);
? }
? public boolean accept(File dir, String name) {
??? // 判斷名為 name 的文件是不是符合過濾條件
??? return pattern.matcher(new File(name).getName()).matches();/*matches() 嘗試將整個區(qū)域 / 與模式匹配。 new File(name).getName() 得到 String 類的 name*/
? }
}
運行結(jié)果 :