How to get all the image files from a folder in Java?

Filter Image files from folder

Filter image files from a folder in Java

Let’s see how to filter-out only image files from a directory in Java. We will write code to iterate through all the files present in a directory, and then filter out only the image files by their extension. In the following example snippet, .jpg, .png, .gif and .webp images will be selected from the given folder.

  • Pass the directory from which images should be found as the parameter
  • Specify the image extension for the required images in the list supportedImageExtensions
private List<File> getAllImageFilesFromFolder(File directory) {
  //Get all the files from the folder
  File[] allFiles = directory.listFiles();
  if (allFiles == null || allFiles.length == 0) {
    throw new RuntimeException("No files present in the directory: " + directory.getAbsolutePath());
  }

  //Set the required image extensions here.
  List<String> supportedImageExtensions = Arrays.asList("jpg", "png", "gif", "webp");

  //Filter out only image files
  List<File> acceptedImages = new ArrayList<>();
  for (File file : allFiles) {
    //Parse the file extension
    String fileExtension = file.getName().substring(file.getName().lastIndexOf(".") + 1);
    //Check if the extension is listed in the supportedImageExtensions
    if (supportedImageExtensions.stream().anyMatch(fileExtension::equalsIgnoreCase)) {
      //Add the image to the filtered list
      acceptedImages.add(file);
    }
  }

  //Return the filtered images
  return acceptedImages;
}
Muhammed Afsal Villan
Muhammed Afsal Villan is an experienced full-stack developer, specialized in desktop and mobile application development. He also regularly publishes quality tutorials on his YouTube channel named 'Genuine Coder'. He likes to contribute to open-source projects and is always enthusiastic about new technologies.

2 COMMENTS