Filter Image files from folder

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

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.

More From Author

Java GIF Tutorial

Create animated GIF from multiple images in Java

Flutter TextButton Widget – Usage and Examples

53 thoughts on “How to get all the image files from a folder in Java?

  1. Pingback: KIOTO Solarmodul
  2. Pingback: bola808 live
  3. Pingback: ks quik
  4. Pingback: naga356
  5. Pingback: golden visa
  6. Pingback: tải go88
  7. Pingback: avsubthai
  8. Pingback: Vape carts
  9. Pingback: lazywin888
  10. Pingback: โคมไฟ
  11. Pingback: Sevink Molen
  12. Pingback: altogel
  13. Pingback: graphite crypto
  14. Pingback: ufabet789
  15. Pingback: pgslot168
  16. Pingback: dultogel
  17. Pingback: pgslot
  18. Pingback: rich89bet

Leave a Reply