How to get the list of jpg files in a directory in Java?


The String[] list(FilenameFilter filter) method of a File class returns a String array containing the names of all the files and directories in the path represented by the current (File) object. But the retuned array contains the filenames which are filtered based on the specified filter. The FilenameFilter is an interface in Java with a single method.

accept(File dir, String name)

To get the file names based on extensions implement this interface as such and pass its object to the above specified list() method of the file class.

Assume we have a folder named ExampleDirectory in the directory D with 7 files and 2 directories as −

Example

The following Java program prints the names of the text files and jpeg files in the path D:\ExampleDirectory separately.

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);
      }  
   }
}

Output

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

Example

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);
    }
}

Output

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

Updated on: 08-Feb-2021

778 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements