How do I get an array of files based on a file suffix?
Author: Deron Eriksson
Description: This Java tutorial describes how to filter files based on a filename suffix.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


The SuffixFileFilter class in the ApacheSW Commons IOS library can be used to filter files based on a particular suffix. This can be performed using case sensitivity or case insensitivity. The SuffixFileFilterTest class demonstrates filtering files based on suffixes using singleton instance filters in SuffixFileFilter.

SuffixFileFilterTest.java

package test;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.SuffixFileFilter;

public class SuffixFileFilterTest {

	public static void main(String[] args) throws IOException {
		File directory = new File(".");

		File[] files = directory.listFiles();
		System.out.println("All files and directories:");
		displayFiles(files);

		System.out.println("\nFiles ending with '.txt' (case sensitive):");
		files = directory.listFiles((FileFilter) new SuffixFileFilter(".txt", IOCase.SENSITIVE));
		displayFiles(files);

		System.out.println("\nFiles ending with '.txt' (case insensitive):");
		files = directory.listFiles((FileFilter) new SuffixFileFilter(".txt", IOCase.INSENSITIVE));
		displayFiles(files);

	}

	public static void displayFiles(File[] files) {
		for (File file : files) {
			System.out.println(file.getName());
		}
	}

}

The results of executing SuffixFileFilterTest are shown below.

Results

All files and directories:
.classpath
.project
bin
docs
lib
src
Test1.txt
test2.TXT
Test3.jsp
test4.JSP

Files ending with '.txt' (case sensitive):
Test1.txt

Files ending with '.txt' (case insensitive):
Test1.txt
test2.TXT