10.9. Filtering Files
Problem
You need to select all the files
in a directory ending in .xml
, or you need to
select only files (not subdirectories) contained in a directory. In
other words, you need to filter a list of files.
Solution
Use one of the many implementations of
IOFileFilter
in the org.apache.commons.io.filefilter
package.
This package contains various implementations of
FileFilter
and FilenameFilter
,
which can be used to filter the contents of a directory. The
following example uses SuffixFileFilter
to return
an array of filenames that end in .xml
:
import java.io.FilenameFilter; import org.apache.commons.io.filefilter.SuffixFileFilter; import org.apache.commons.lang.ArrayUtils; File rootDir = new File("."); FilenameFilter fileFilter = new SuffixFileFilter(".xml"); String[] xmlFiles = rootDir.list( fileFilter ); System.out.println( "*** XML Files" ); System.out.println( ArrayUtils.toString( xmlFiles ) );
This code searches for all files ending in .xml
in the current directory. Running this in the root of the example
project matches one file, project.xml
, producing
the following output:
*** XML Files {project.xml}
Discussion
The
org.apache.commons.io.filefilter
package contains a number of
implementations of FilenameFilter
and
FileFilter
. PrefixFileFilter
and SuffixFileFilter
let you match files and
directories by a prefix or suffix. NameFileFilter
matches a file or a directory to a specific name.
DirectoryFileFilter
accepts only directories.
AndFileFilter
, OrFileFilter ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.