Duffblog

          前進一步,看看,需要前進更大一步才可以。

            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            5 隨筆 :: 53 文章 :: 5 評論 :: 0 Trackbacks
          我想要讀取某一個路徑下,文件最后修改的時間大于我給定的所有的文件.
          比如是E:\file
          我想要等到一部分的file,即是文件最后修改的時間大于我給定的
          我目前的做法是:
          查看所有的File,一一比對,得到我想要的File
          //read path
          Vector needReadFile = new Vector();
          Date fileDate = new Date();
          File[] files = new File(readFilePath).listFiles();
          if (files == null) {
          continue;
          }
          for (int x = 0; x < files.length; x++) {
          File tempFile = files[x];
          Date fileDate = new Date(tempFile.
          lastModified());
          if (fileDate.compare(lastModifyDate) == 1 ) {
          needReadFile.add(readFilePath + File.separator +
          tempFile.getName());
          }
          } //end for(int i = 0 ; i< files.length ; i++)

          雖然這樣做是可以達到,當(dāng)我的File很多的時候,效率很差了

          效率好一點的方法:

          看看listFiles()和listFiles(FileFilter filter) 的源代碼

          public File[] listFiles() {
          String[] ss = list();
          if (ss == null) return null;
          int n = ss.length;
          File[] fs = new File[n];
          for (int i = 0; i < n; i++) {
          fs[i] = new File(this.path, ss[i]);
          }
          return fs;
          }

          public File[] listFiles(FileFilter filter) {
          String ss[] = list();
          if (ss == null) return null;
          ArrayList v = new ArrayList();
          for (int i = 0 ; i < ss.length ; i++) {
          File f = new File(this.path, ss[i]);
          if ((filter == null) || filter.accept(f)) {
          v.add(f);
          }
          }
          return (File[])(v.toArray(new File[0]));
          }

          采用第二個方法以后,只需要遍歷一遍,而且代碼更清晰,
          采用第一個方法,你取得列表以后還需要遍歷一遍過濾掉不符合條件的.

          File[] files = new File(readFilePath).listFiles(new FileFilter(){
          public boolean accept(File pathname){
          //.判斷修改日期,符合條件返回true;否則false;

          }});

          這里采用匿名類,實現(xiàn)一個FileFilter,你要修改過濾的邏輯,只需要修改accept()方法就是了,當(dāng)然,你也可以專門寫一個類比如

          class FileModifyDateFilter implements FileFilter{
          private Date baseDate = null;
          public FileModifyDateFilter(Date d) {
          baseDate = d;
          }

          public boolean accept(File f) {
          if (baseDate == null)
          return true;
          if (f.lastModified() > baseDate.getTime())
          return true;

          return false;
          }
          }


          原文來自:http://www.jdon.com/jive/thread.jsp?forum=16&thread=22478&message=13169392
          posted on 2006-04-04 21:17 追球者 閱讀(849) 評論(0)  編輯  收藏 所屬分類: Java
          主站蜘蛛池模板: 黄浦区| 明水县| 长宁县| 尉犁县| 措勤县| 淳安县| 苗栗市| 姜堰市| 无棣县| 新龙县| 易门县| 丹棱县| 林周县| 伊宁县| 高雄市| 盐津县| 昌平区| 武功县| 新丰县| 扬州市| 霸州市| 高陵县| 津市市| 长泰县| 丰台区| 社旗县| 东乌珠穆沁旗| 德阳市| 黑龙江省| 蒙自县| 宿迁市| 建始县| 贵南县| 厦门市| 兴文县| 措勤县| 阜康市| 清徐县| 新宾| 凉城县| 凌海市|