How to get all files with certain extension in a folder in java

In this post, we will see how to list all files with certain extension in a folder.
For example, you want to list all .jpg or .zip files in a folder.

We will  use FilenameFilter interface to list the files in a folder, so we will create a inner class which will implement FilenameFilter interface and implement accept method. We need to pass created inner class to java.io.File 's list method to list all files with specific extension.

Java Program :
package org.arpit.java2blog;

import java.io.File;
import java.io.FilenameFilter;

public class GetAllFilesWithCertainExtMain {
 /*
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {

  GetAllFilesWithCertainExtMain main=new GetAllFilesWithCertainExtMain();
  System.out.println("Finding .zip files in the folder /Users/Arpit/Desktop/Blog");
  System.out.println("-----------------");
  // Read the file
  File folder=new File("/Users/Arpit/Desktop/Blog");
  main.getAllFilesWithCertainExtension(folder,"zip");
  
  System.out.println("-----------------");
 }
 
 public  void getAllFilesWithCertainExtension(File folder,String filterExt)
 {
  MyExtFilter extFilter=new MyExtFilter(filterExt);
  if(!folder.isDirectory())
  {
   System.out.println("Not a folder");
  }
  else
  {
   // list out all the file name and filter by the extension
   String[] list = folder.list(extFilter);

   if (list.length == 0) {
    System.out.println("no files end with : " + filterExt);
    return;
   }

   for (int i = 0; i < list.length; i++) {
    System.out.println("File :"+list[i]);
   }
  }
 }
 
 // inner class, generic extension filter
  public class MyExtFilter implements FilenameFilter {

   private String ext;

   public MyExtFilter(String ext) {
    this.ext = ext;
   }

   public boolean accept(File dir, String name) {
    return (name.endsWith(ext));
   }
  }
}

When I ran above program, I got following output:
Finding .zip files in the folder /Users/Arpit/Desktop/Blog
-----------------
File :sampleFile1.zip
File :sampleFile2.zip
File :sampleFile3.zip
File :Spring3-Quartz-Example.zip
File :SpringQuartzIntegrationExample.zip
-----------------

So we have found all .zip file in folder "/Users/Arpit/Desktop/Blog"

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012