如何用 Java 查詢檔案?


以下示例演示了透過建立檔案篩選器在目錄中查詢特定檔案的方法。以下示例顯示了所有以“b”開頭的檔名。

示例

即時演示

import java.io.*;

public class Main {
   public static void main(String[] args) {
      File dir = new File("C:");
     
      FilenameFilter filter = new FilenameFilter() {
         public boolean accept (File dir, String name) {
            return name.startsWith("b");
         }
      };
      String[] children = dir.list(filter);

      if (children == null) {
         System.out.println("Either dir does not exist or is not a directory");
      } else {
         for (int i=0; i< children.length; i++) {
            String filename = children[i];
            System.out.println(filename);
        }
      }
   }
}

輸出

build
build.xml

更新日期:2019 年 7 月 30 日

115 次瀏覽

開啟你的 事業

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.