How do I search for files recursively?
Category: commons.io, viewed: 22814 time(s).
This example demonstrate how we can use the FileUtils class listFiles() method to search for a file specified by their extensions. We can also define to find the file recursively deep down into the subdirectories.
package org.kodejava.example.commons.io;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.util.Collection;
import java.util.Iterator;
public class SearchFileRecursive {
public static void main(String[] args) {
File root = new File("/home/foobar/Personal/Examples");
try {
String[] extensions = {"xml", "java", "dat"};
boolean recursive = true;
//
// Finds files within a root directory and optionally its
// subdirectories which match an array of extensions. When the
// extensions is null all files will be returned.
//
// This method will returns matched file as java.io.File
//
Collection files = FileUtils.listFiles(root, extensions, recursive);
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
System.out.println("File = " + file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Download Hundreds of Complimentary Industry Resources
Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more;
all available at no cost to you. With more than 600 complimentary offers, you'll find
plenty of titles to suit your professional interests and needs.
Click Here and Sign up today!