If you want to list out all files from a given directory or drive you can use the list method in the java.io.File class. Consider a scenario where you wanted to list out all files with specific extension. FileFilter interface will help you to filter files using any criteria you can imagine. Today we will look at the use of FileFilter interface with a simple example. Given below example will recursively list out all java files in the given location and given extension.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.ourownjava.corejava.file; import java.io.File; import java.io.FileFilter; /** * @author ourownjava.com * @date 31st July, 2011 * * How to filter file in java? * FileFilter example in java. * */ public class FileExtensionFilter implements FileFilter { private String extension; public FileExtensionFilter(final String extension) { this.extension = extension; } public boolean accept(final File pathname) { boolean accept = false; if (null != pathname) { accept = pathname.getAbsolutePath().endsWith(extension); } return accept; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package com.ourownjava.corejava.file; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author ourownjava.com * @date 31st July, 2011 * * How to filter file in java? * FileFilter example in java. * */ public class FileFilteringExample { public static void main(final String args[]) { final FileExtensionFilter filter = new FileExtensionFilter(".java"); final List<File> javaFiles = new ArrayList<File>(); new FileFilteringExample().findUsingExtension(new File("/local/opt"), filter, javaFiles); System.out.println("Found " + javaFiles.size() + " java files in /local/opt"); for (final File file : javaFiles) { System.out.println(file.getAbsolutePath()); } } private void findUsingExtension(final File file, final FileFilter filter, final List<File> files) { if (file.isDirectory()) { final File[] filteredFiles = file.listFiles(filter); if (null != filteredFiles) { files.addAll(Arrays.asList(filteredFiles)); } for (final File childFile : file.listFiles()) { if (null != childFile) { findUsingExtension(childFile, filter, files); } } } } } |
Console Output.
1 2 3 4 5 6 |
Found 7999 java files in /local/opt /local/opt/apache-activemq-5.2.0 /local/opt/apache-ant-1.7.1 /local/opt/apache-tomcat-6.0.18-src /local/opt/apache-tomcat-6.0.32 ............... |
Pingback: How to filter files in java? | Clean Java