Home » Core Java » io » FilenameFilter » Java FilenameFilter Example

About Nikos Maravitsas

Nikos Maravitsas
Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. 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

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.