How do I select files to a particular depth in a directory?
Author: Deron Eriksson
Description: This Java tutorial describes how to select files down to a particular depth in a directory using Commons IO.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)
Extending the DirectoryWalker class in the ApacheSW Commons IOS library is a handy way to perform powerful file selection capabilities. The DirectoryWalkerTest class illustrates this. It returns all *.txt files in my project's "stuff" directory at a directory depth of 3 or less. DirectoryWalkerTest features a MyDirectoryWalker inner class that extends DirectoryWalker. Of particular note are the handleFile() method, which is executed when a file is encountered, and handleDirectory(), which is executed when a directory is encountered. Also notice that the actual 'walking' is performed when the walk() method is invoked. DirectoryWalkerTest.javapackage test; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.io.DirectoryWalker; public class DirectoryWalkerTest { public static void main(String[] args) throws IOException { File dir = new File("C:\\projects\\workspace\\testing\\stuff"); MyDirectoryWalker walker = new MyDirectoryWalker(); List<File> txtFiles = walker.getTxtFiles(dir); System.out.println("\nFiles ending with .txt with a depth of 3 or less"); for (File txtFile : txtFiles) { System.out.println("file:" + txtFile.getCanonicalPath()); } } public static class MyDirectoryWalker extends DirectoryWalker { public MyDirectoryWalker() { super(); } public List<File> getTxtFiles(File dir) throws IOException { List<File> results = new ArrayList<File>(); walk(dir, results); return results; } protected void handleFile(File file, int depth, Collection results) throws IOException { if (file.getCanonicalPath().endsWith(".txt")) { if (depth > 3) { System.out.println("depth is " + depth + ", so " + file.getCanonicalPath() + " will be skipped"); } else { System.out.println("depth is " + depth + ", so " + file.getCanonicalPath() + " will be added"); results.add(file); } } else { System.out.println("file doesn't end in .txt, so " + file.getCanonicalPath() + " will be skipped"); } } protected boolean handleDirectory(File directory, int depth, Collection results) { return true; } } } (Continued on page 2) Related Tutorials:
|