Quantcast
Channel: Gubatron.com
Viewing all articles
Browse latest Browse all 165

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

$
0
0

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


Viewing all articles
Browse latest Browse all 165

Latest Images

Trending Articles



Latest Images