Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Apache Commons DirectoryWalker?

I am trying to figure out how to use Apache Commons IO DirectoryWalker. It's pretty easy to understand how to subclass DirectoryWalker.

But how do you start executing it on a particular directory?

like image 498
Jason S Avatar asked Jul 07 '09 00:07

Jason S


1 Answers

Just to expand on this answer since I was puzzled at first of how to use the class as well and this question came up on google when I was looking around. This is just an example of how I used it (minus some things):

public class FindConfigFilesDirectoryWalker extends DirectoryWalker {
    private static String rootFolder = "/xml_files";
    private Logger log = Logger.getLogger(getClass());

    private static IOFileFilter filter = FileFilterUtils.andFileFilter(FileFilterUtils.fileFileFilter(),
            FileFilterUtils.suffixFileFilter("xml"));

    public FeedFileDirectoryWalker() {
        super(filter, -1);
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void handleFile(final File file, final int depth, final Collection results) throws IOException {
        log.debug("Found file: " + file.getAbsolutePath());
        results.add(file);
    }

    public List<File> getFiles() {
        List<File> files = new ArrayList<File>();

        URL url = getClass().getResource(rootFolder);

        if (url == null) {
            log.warn("Unable to find root folder of configuration files!");
            return files;
        }

        File directory = new File(url.getFile());

        try {
            walk(directory, files);
        }
        catch (IOException e) {
            log.error("Problem finding configuration files!", e);
        }

        return files;
    }
}

And then you would just invoke it via the public method you created, passing in any arguments that you may want:

List<File> files = new FindConfigFilesDirectoryWalker().getFiles();
like image 182
rcl Avatar answered Dec 11 '22 04:12

rcl