FilenameFilter

Java File Filter Example

Usually there is a need of filtering files into our app and/or show only specific type of files to the users. So, we can limit the appearance of the files with the use of FilenameFilter interface. This could be useful when we have to deal with large file systems or facilitate the user to select a file.

In this example we are going to show you how to filter files with a specific extension, by using the FilenameFilter interface.

 
 
 

1. Create the FilenameFilter interface

Create a new java file with the name MyFileFilterClass into the package com.javacodegeeks.javacore.filefilter. Then paste the following code.

MyFileFilterClass.java:

package com.javacodegeeks.javacore.filefilter;

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

public class MyFileFilterClass implements FilenameFilter {

	private String[] extensionArray = {"txt", "pdf"};
	
	@Override
	public boolean accept(File dir, String name) {
		
		if(dir.exists()) {
			for(String ext : extensionArray) {
				if(name.endsWith(ext))
					return true;
			}
		}
		return false;
	}

}

This class implements the FilenameFilter and overrides the accept() method. FilenameFilter interface help us to filter files with a specified extension. accept() operation checks whether the file, that is characterized by the arguments (its directory and its name), should be included into a file list. The check is based on the conditions we set. In our example, we accept the files that end with one of the strings that are declared into the extensionArraytxt or pdf files only. All the other files are rejected, so false is returned at this situation.

2. Create the Main Class

Now let’s create a new class that will contain a MyFileFilterClass instance. Specify the name of the java file – FileFilterMain – and put it into the com.javacodegeeks.javacore.filefilter package. Then paste the following code.

FileFilterMain.java:

package com.javacodegeeks.javacore.filefilter;

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

public class FileFilterMain {
	
	private static String PATH = "C://JCGFolder";

	public static void main(String[] args) {
		
		File myFile = new File(PATH);
		
		if(!myFile.exists()) {
			System.out.println("The file does not exist...");
			System.exit(1);
		}
		FilenameFilter filter = new MyFileFilterClass();
		
		// a list that contains only files with the specified extension
		File[] fileList = myFile.listFiles(filter);
		
		if(fileList.length > 0) {
			System.out.println("Containing files with the use of filter are:");
			
			for(File file : fileList) {
				System.out.println(file.getAbsolutePath());
			}
		} else {
			System.out.println("There are not such files into the "+myFile);
		}
		
		System.out.println("---------------------------------------------------");
		
		// list without a file filter
		File[] listNoExt = myFile.listFiles();
		
		if(fileList.length > 0) {
			System.out.println("Containing files without the filter are:");
			
			for(File file : listNoExt) {
				System.out.println(file.getAbsolutePath());
			}
		} else {
			System.out.println("There are no files at all");
		}

	}

}

As you can notice from the code above, after the creation of the MyFileFilterClass instance we invoke listFiles() function of the java.io.File class, by passing the MyFileFilterClass instance as an argument. With this way, we get a list of Files – fileList – that includes only the files with the specific extension.

If we call again listFiles() method without using a filter, the file list will contain all the files of the specified folder.

You can also have a look at the execution of the code above, for further comprehension.

Output:

Containing files with the use of filter are:
C:\JCGFolder\jcg.txt
C:\JCGFolder\test.pdf
---------------------------------------------------
Containing files without the filter are:
C:\JCGFolder\imageTXT.jpg
C:\JCGFolder\jcg.txt
C:\JCGFolder\readme.odt
C:\JCGFolder\test.pdf

It is important to mention that the filtering can be more complex. For example we can use regular expressions and filter files that have only letters etc. Nevertheless, our filtering conditions are set into the accept() method of the FilenameFilter class.

Download the Eclipse Project

This was an example of file filter in Java.

Download
You can download the full source code of this example here : FileFilterExample.zip

Katerina Zamani

Katerina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she attends MSc courses in Advanced Information Systems at the same department. Currently, her main academic interests focus on web applications, mobile development, software engineering, databases and telecommunications.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button