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.
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 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
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:
1 2 3 4 5 6 7 8 9 10 |
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”
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.