java: How to get all the files inside a folder and its subfolders without recursion

March 19th, 2013 4 minutes reading time.


Most programmers will do this in a recursive fashion, but doing that is putting yourself at risk of hitting a stack overflow error, and it’s 20% slower (according to my tests). Here’s my first implementation of a method that will return just the files (cause I didn’t need the folders, you can always hack it to your needs). This is part of FrostWire for Android and FrostWire for Desktop, all the code is available under the GPL at our github repository.

/** Given a folder path it'll return all the files contained within it and it's subfolders
     * as a flat set of Files.
     * 
     * Non-recursive implementation, up to 20% faster in tests than recursive implementation. :) 
     * 
     * @author gubatron
     * @param folder
     * @param extensions If you only need certain files filtered by their extensions, use this string array (without the "."). or set to null if you want all files. e.g. ["txt","jpg"] if you only want text files and jpegs.
     * 
     * @return The set of files.
     */
    public static Collection<File> getAllFolderFiles(File folder, String[] extensions) {
        Set<File> results = new HashSet<File>();
        Stack<File> subFolders = new Stack<File>();
        File currentFolder = folder;
        while (currentFolder != null && currentFolder.isDirectory() && currentFolder.canRead()) {
            File[] fs = null;
            try {
                fs = currentFolder.listFiles();
            } catch (SecurityException e) {
            }
            
            if (fs != null && fs.length > 0) {
                for (File f : fs) {
                    if (!f.isDirectory()) {
                        if (extensions == null || FilenameUtils.isExtension(f.getName(), extensions)) {
                            results.add(f);
                        }
                    } else {
                        subFolders.push(f);
                    }
                }
            }
            
            if (!subFolders.isEmpty()) {
                currentFolder = subFolders.pop();
            } else {
                currentFolder = null;
            }
        }
        return results;
    }    

Here’s the FilenameUtils if you want the isExtension() implementation and it’s dependencies, you can always code your own there

Please Donate To Bitcoin Address: [[address]]

Donation of [[value]] BTC Received. Thank You.
[[error]]

Leave a Reply