In this section, we will be showing a java source code that list filenames in a folder based or fileterd on the filename extension. The approach would be to make use of File class under java.io package and use its constructor in declaring the directory that we want to look at. The listFiles method of File class would be able to list out the filenames under the folder declared in the constructor. However our concern is to list filenames of specific extension. This can be attained using the FilenameFilter of java.io package.

List filenames filtered by filename extension

The FilenameFilter of java.io package is an interface. This interface class filters out the filename based on the implementation of accept method. This method accepts File dir and string name. Moreover it returns a boolean which tells if the passed parameter is passed the test of including it on the list of filenames.

package com.javatutorialhq.tutorial;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SearchFileExtension {

	/**
	 * This java sample code shows
	 * how to list files in fileter by extension using FileNameFilter
	 * Property of javatutorialhq.com
	 * All Rights Reserved
	 * Version 1.0
	 * 08/01/2012
	 */
	public static void main(String[] args) {
		File file = new File("D:\\Websites");
		//check first if supplied file name is a folder
		if(file.isDirectory()){
			List listFile = new ArrayList<>();
			listFile = Arrays.asList(file.listFiles(new FilenameFilter() {
				@Override
				public boolean accept(File dir, String name) {
					return name.toLowerCase().endsWith(".whtt");
				}
			}));
			for(File f:listFile){
				System.out.println(f.getAbsolutePath());
			}
		}
		else{
			//Flagging down that the filename specified is not a directory
			System.out.println("file "+file.getAbsolutePath()+" is not a directory");
		}

	}

}