Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Java FilenameFilter Example

In this example we are going to talk about Java FilenameFilter interface. FilenameFilter is a very convenient interface that helps you filter out specific file names when listing a folder. So, as you might imagine, it is particularly useful for applications that have to navigate through big file systems.

Filter file extension

In order to use the FilenameFilter class to filter file names, you have to create a class that implements FilenameFilter and override its accept method.
 
 

MyFileFilter.java:

package com.javacodegeeks.core.io.filenamefilter;

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

public class MyFileFilter implements FilenameFilter {
	
	@Override
	public boolean accept(File directory, String fileName) {
		if (fileName.endsWith(".txt")) {
            return true;
        }
        return false;
	}
}

In the above accept method you can see too arguments. The first File argument is the folder that is being listed and the second one is the name of the file that is being checked. In this method you can check the file name and directory and create a filter that accepts or rejects based on your own conditions. In this example we accept a file if it ends with ".txt".

And you can simply use it like so:

FileFilterExample.java:

package com.javacodegeeks.core.io.filenamefilter;

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

public class FileFilterExample {
	
	private static final String FOLDER_PATH ="F:\\nikos7\\Desktop\\testFiles"; 

	public static void main(String[] args){
		
		File dir = new File(FOLDER_PATH);
		
		FilenameFilter filter = new MyFileFilter();
		
		File[] files = dir.listFiles(filter);
		
		for(File f : files)
			System.out.println(f.getName());	
	}
}

Output:

javacodegeeks.txt
jisea.txt
textFile.txt

If you run this program without the filter :

FileFilterExample.java:

package com.javacodegeeks.core.io.filenamefilter;

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

public class FileFilterExample {
	
	private static final String FOLDER_PATH ="F:\\nikos7\\Desktop\\testFiles"; 

	public static void main(String[] args){
		
		File dir = new File(FOLDER_PATH);
		
		FilenameFilter filter = new MyFileFilter();
		
		File[] files = dir.listFiles();
		
		for(File f : files)
			System.out.println(f.getName());	
	}
}

Output:

2010.docx
20140116_151426.jpg
31-10-2013 4-38-36 ??.jpg
javacodegeeks.txt
jisea.txt
pointer.pdf
taxis.jpg
textFile.txt

So as you can see, when you use the filter you only get files with the ".txt" extension.

If you want, of course you can provide the FilenameFilter as an anonymous class:
FileFilterExample.java:

package com.javacodegeeks.core.io.filenamefilter;

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

public class FileFilterExample {
	
	private static final String FOLDER_PATH ="F:\\nikos7\\Desktop\\testFiles"; 

	public static void main(String[] args){
		
		File dir = new File(FOLDER_PATH);
			
		File[] files = dir.listFiles(new FilenameFilter(){

			@Override
			public boolean accept(File directory, String fileName) {
				if (fileName.endsWith(".txt")) {
		            return true;
		        }
		        return false;
			}
		} );
		
		for(File f : files)
			System.out.println(f.getName());
	}
}

Filter file name using regular expressions

Of course, you can make more complex filter than the above one, using regular expressions. For example, I want to list all the files that do not contain number in their names.

FileFilterExample.java:

package com.javacodegeeks.core.io.filenamefilter;

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

public class FileFilterExample {
	
	private static final String FOLDER_PATH ="F:\\nikos7\\Desktop\\testFiles"; 

	public static void main(String[] args){
		
		File dir = new File(FOLDER_PATH);
			
		File[] files = dir.listFiles(new FilenameFilter(){

			@Override
			public boolean accept(File directory, String fileName) {
				if (fileName.matches("[a-zA-z]+\\.[a-z]+")) {
		            return true;
		        }
		        return false;
			}
			
		} );
		
		for(File f : files)
			System.out.println(f.getName());
	}
}

Output:

javacodegeeks.txt
jisea.txt
taxis.jpg
textFile.txt

Download Source Code

This was a FilenameFilter example. You can download the source code of this example here : FileFilterExample.zip

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books