posts - 44,  comments - 48,  trackbacks - 0

          目錄列示器

          本實例演示如何得到一個目錄下的所有文件列表 .

          1.?????? 這里利用了 DirFilter 實現了 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{

          ????? // 這里將輸入的參數作為過濾因子

          ????? 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() 嘗試將整個區域 / 與模式匹配。 new File(name).getName() 得到 String 類的 name*/

          ? }

          }

          運行結果 :

          Image00003.jpg

          posted on 2006-08-24 19:29 摩西 閱讀(230) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 东明县| 汽车| 天柱县| 泗洪县| 永善县| 吉木乃县| 大埔区| 抚松县| 台江县| 修武县| 英吉沙县| 阳谷县| 清镇市| 梨树县| 临海市| 陆川县| 永兴县| 洛宁县| 宜昌市| 北宁市| 兴和县| 读书| 玉溪市| 于都县| 迭部县| 阳信县| 银川市| 南康市| 酒泉市| 宜黄县| 阿拉善右旗| 万州区| 台湾省| 德化县| 兴义市| 峨眉山市| 多伦县| 岳西县| 原阳县| 枞阳县| 永泰县|