How do I get an array of files based on a file prefix?
Author: Deron Eriksson
Description: This Java tutorial describes how to filter files based on a filename prefix.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)
The PrefixFileFilter in the ApacheSW Commons IOS library makes it easy to filter files to obtain files with a particular prefix. This can be done using case sensitivity or case insensitivity. The PrefixFileFilterTest class demonstrates calling a directory's listFiles() method with PrefixFileFilter objects serving as filters. PrefixFileFilterTest.javapackage 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.PrefixFileFilter; public class PrefixFileFilterTest { 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 beginning with 'Test' (case sensitive):"); files = directory.listFiles((FileFilter) new PrefixFileFilter("Test", IOCase.SENSITIVE)); displayFiles(files); System.out.println("\nFiles beginning with 'Test' (case insensitive):"); files = directory.listFiles((FileFilter) new PrefixFileFilter("Test", IOCase.INSENSITIVE)); displayFiles(files); } public static void displayFiles(File[] files) { for (File file : files) { System.out.println(file.getName()); } } } The PrefixFileFilterTest class first displays all files in my project's root directory. After that, it displays all files beginning with "Test" with case sensitivity. Finally, it displays all files beginning with "Test" but with case insensitivity. ResultsAll files and directories: .classpath .project bin docs lib src Test1.txt test2.txt Test3.txt test4.txt Files beginning with 'Test' (case sensitive): Test1.txt Test3.txt Files beginning with 'Test' (case insensitive): Test1.txt test2.txt Test3.txt test4.txt Related Tutorials:
|