如何在Java中獲取目錄下所有jpg檔案的列表?


File類的**String[] list(FilenameFilter filter)**方法返回一個字串陣列,其中包含當前(File)物件所表示路徑中的所有檔案和目錄的名稱。但是,返回的陣列包含基於指定過濾器過濾的檔名。**FilenameFilter**是Java中的一個介面,只有一個方法。

accept(File dir, String name)

要根據副檔名獲取檔名,請按如下方式實現此介面並將它的物件傳遞給上面指定的File類的list()方法。

假設我們在D盤目錄下有一個名為*ExampleDirectory*的資料夾,其中包含7個檔案和2個目錄,如下所示:

示例

下面的Java程式分別列印D:\ExampleDirectory路徑中文字檔案和jpeg檔案的名稱。

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
public class Sample{
   public static void main(String args[]) throws IOException {
    //Creating a File object for directory
    File directoryPath = new File("D:\ExampleDirectory");
    //Creating filter for jpg files
    FilenameFilter jpgFilefilter = new FilenameFilter(){
         public boolean accept(File dir, String name) {
            String lowercaseName = name.toLowerCase();
            if (lowercaseName.endsWith(".jpg")) {
               return true;
            } else {
               return false;
            }
         }
      };        
      String imageFilesList[] = directoryPath.list(jpgFilefilter);
      System.out.println("List of the jpeg files in the specified directory:");  
      for(String fileName : imageFilesList) {
         System.out.println(fileName);
      }  
   }
}

輸出

List of the jpeg files in the specified directory:
cassandra_logo.jpg
cat.jpg
coffeescript_logo.jpg
javafx_logo.jpg

示例

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class Example {
   public static void main(String[] args) throws IOException {
      Stream<Path> path = Files.walk(Paths.get("D:\ExampleDirectory"));
      path = path.filter(var -> var.toString().endsWith(".jpg"));
      path.forEach(System.out::println);
    }
}

輸出

List of the jpeg files in the specified directory:
cassandra_logo.jpg
cat.jpg
coffeescript_logo.jpg
javafx_logo.jpg

更新於:2021年2月8日

瀏覽量:1K+

啟動您的職業生涯

完成課程獲得認證

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