In this tutorial, we will see how to find all the files with certain extensions in the specified directory.
Program: Searching all files with “.png” extension
In this program, we are searching all “.png” files in the “Documents” directory(folder). I have placed three files Image1.png, Image2.png, Image3.png in the Documents directory.
Similarly, we can search files with the other extensions like “.jpeg”,”jpg”,”.xml”,”.txt” etc.
package com.beginnersbook;
import java.io.*;
public class FindFilesWithThisExtn {
//specify the path (folder) where you want to search files
private static final String fileLocation = "/Users/chaitanyasingh/Documents";
//extension you want to search for e.g. .png, .jpeg, .xml etc
private static final String searchThisExtn = ".png";
public static void main(String args[]) {
FindFilesWithThisExtn obj = new FindFilesWithThisExtn();
obj.listFiles(fileLocation, searchThisExtn);
}
public void listFiles(String loc, String extn) {
SearchFiles files = new SearchFiles(extn);
File folder = new File(loc);
if(folder.isDirectory()==false){
System.out.println("Folder does not exists: " + fileLocation);
return;
}
String[] list = folder.list(files);
if (list.length == 0) {
System.out.println("There are no files with " + extn + " Extension");
return;
}
for (String file : list) {
String temp = new StringBuffer(fileLocation).append(File.separator)
.append(file).toString();
System.out.println("file : " + temp);
}
}
public class SearchFiles implements FilenameFilter {
private String ext;
public SearchFiles(String ext) {
this.ext = ext;
}
@Override
public boolean accept(File loc, String name) {
if(name.lastIndexOf('.')>0)
{
// get last index for '.'
int lastIndex = name.lastIndexOf('.');
// get extension
String str = name.substring(lastIndex);
// matching extension
if(str.equalsIgnoreCase(ext))
{
return true;
}
}
return false;
}
}
}
Output:
file : /Users/chaitanyasingh/Documents/Image1.png file : /Users/chaitanyasingh/Documents/Image2.png file : /Users/chaitanyasingh/Documents/Image3.png
Leave a Reply