javarecursionapache-commons-iofile-listing

How can we list all files and folders recursively?


As search via google, and in this SO site, results will come up with FileUtils.listFilesAndDirs() method from Apache Commons IO.

But this method is not going recursively into sub folders - we need recursive file listing.

How can we do it with Commons IO?

P.S.:

A native way to do it is using File.listFiles() natively supported by JDK as solved here.


Solution

  • You can use the FileUtils.listFiles(File base, String[] extensions, boolean recursive).

    To retrieve all of the files set recursive to true and extensions to null.

     FileUtils.listFiles(basePath, null, true);
    

    Alternatively, using the other overides of FileUtils.listFiles, you can provide more detailed search parameters.

    If you want to find both files AND directories instead of only files, use the

     FileUtils.listFilesAndDirs(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter)
    

    See here for more detail.

    Example call

    FileUtils.listFilesAndDirs(basePath, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)