How do I use a FilenameFilter to display a subset of files in a directory?
Author: Deron Eriksson
Description: This Java tutorial describes how to use a FilenameFilter to display a subset of files in a directory.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)
FilenameFilter is an interface in JavaSW that is used to filter file names, such as those returned from a call to a File object's listFiles() method. If listFiles() is called with no parameters, it returns all File objects in a directory. If we pass in a filter as a parameter, we can selectively return a subset of those objects. Creating an object that implements FilenameFilter requires us to implement the accept(File dir, String name) method. The dir object is the parent directory of the file, and name is the name of the file. If accept() returns true, the file will be returned in the array of File objects from the call to listFiles(). If accept() returns false, the file isn't returned by the call to listFiles(). The textFilter object in DirectoryContents returns true only if a File object ends in .txt. As a result, it rejects all other file and directory names. Notice that the call to f.listFiles() passes the textFilter as an argument. DirectoryContents.javapackage test; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; public class DirectoryContents { public static void main(String[] args) throws IOException { File f = new File("."); // current directory FilenameFilter textFilter = new FilenameFilter() { public boolean accept(File dir, String name) { String lowercaseName = name.toLowerCase(); if (lowercaseName.endsWith(".txt")) { return true; } else { return false; } } }; File[] files = f.listFiles(textFilter); for (File file : files) { if (file.isDirectory()) { System.out.print("directory:"); } else { System.out.print(" file:"); } System.out.println(file.getCanonicalPath()); } } } Executing DirectoryContents results in the following console output. Even though other files and directories are present in C:\projects\workspace\testing\, only the .txt files show up in the results. file:C:\projects\workspace\testing\file1.txt file:C:\projects\workspace\testing\file2.txt Related Tutorials:
|