How to scan a folder in Java?

JavaFileDirectory

Java Problem Overview


How can I get list all the files within a folder recursively in Java?

Java Solutions


Solution 1 - Java

Not sure how you want to represent the tree? Anyway here's an example which scans the entire subtree using recursion. Files and directories are treated alike. Note that File.listFiles() returns null for non-directories.

public static void main(String[] args) {
    Collection<File> all = new ArrayList<File>();
    addTree(new File("."), all);
    System.out.println(all);
}

static void addTree(File file, Collection<File> all) {
    File[] children = file.listFiles();
    if (children != null) {
        for (File child : children) {
            all.add(child);
            addTree(child, all);
        }
    }
}

Java 7 offers a couple of improvements. For example, DirectoryStream provides one result at a time - the caller no longer has to wait for all I/O operations to complete before acting. This allows incremental GUI updates, early cancellation, etc.

static void addTree(Path directory, Collection<Path> all)
        throws IOException {
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {
        for (Path child : ds) {
            all.add(child);
            if (Files.isDirectory(child)) {
                addTree(child, all);
            }
        }
    }
}

Note that the dreaded null return value has been replaced by IOException.

Java 7 also offers a tree walker:

static void addTree(Path directory, final Collection<Path> all)
        throws IOException {
    Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException {
            all.add(file);
            return FileVisitResult.CONTINUE;
        }
    });
}

Solution 2 - Java

import java.io.File;
public class Test {
    public static void main( String [] args ) {
        File actual = new File(".");
        for( File f : actual.listFiles()){
            System.out.println( f.getName() );
        }
    }
}

It displays indistinctly files and folders.

See the methods in File class to order them or avoid directory print etc.

http://java.sun.com/javase/6/docs/api/java/io/File.html

Solution 3 - Java

You can also use the [FileFilter][1] interface to filter out what you want. It is best used when you create an anonymous class that implements it:

import java.io.File;
import java.io.FileFilter;

public class ListFiles {
    public File[] findDirectories(File root) { 
        return root.listFiles(new FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory();
            }});
    }

    public File[] findFiles(File root) {
        return root.listFiles(new FileFilter() {
            public boolean accept(File f) {
                return f.isFile();
            }});
    }
}

[1]: http://java.sun.com/javase/6/docs/api/java/io/FileFilter.html "http://java.sun.com/javase/6/docs/api/java/io/FileFilter.html"

Solution 4 - Java

public static void directory(File dir) {
	File[] files = dir.listFiles();
	for (File file : files) {
		System.out.println(file.getAbsolutePath());
		if (file.listFiles() != null)
			directory(file);		
	}
} 

Here dir is Directory to be scanned. e.g. c:\

Solution 5 - Java

Visualizing the tree structure was the most convenient way for me :

public static void main(String[] args) throws IOException {
	printTree(0, new File("START/FROM/DIR"));
}

static void printTree(int depth, File file) throws IOException { 
	StringBuilder indent = new StringBuilder();
	String name = file.getName();

	for (int i = 0; i < depth; i++) {
		indent.append(".");
	}
	
	//Pretty print for directories
	if (file.isDirectory()) { 
		System.out.println(indent.toString() + "|");
		if(isPrintName(name)){
			System.out.println(indent.toString() + "*" + file.getName() + "*");
		}
	}
	//Print file name
	else if(isPrintName(name)) {
		System.out.println(indent.toString() + file.getName()); 
	}
	//Recurse children
	if (file.isDirectory()) { 
		File[] files = file.listFiles(); 
		for (int i = 0; i < files.length; i++){
			printTree(depth + 4, files[i]);
		} 
	}
}

//Exclude some file names
static boolean isPrintName(String name){
	if (name.charAt(0) == '.') {
		return false;
	}
	if (name.contains("svn")) {
		return false;
	}
	//.
	//. Some more exclusions
	//.
	return true;
}

Solution 6 - Java

In JDK7, "more NIO features" should have methods to apply the visitor pattern over a file tree or just the immediate contents of a directory - no need to find all the files in a potentially huge directory before iterating over them.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLipisView Question on Stackoverflow
Solution 1 - JavavolleyView Answer on Stackoverflow
Solution 2 - JavaOscarRyzView Answer on Stackoverflow
Solution 3 - JavaLeonelView Answer on Stackoverflow
Solution 4 - JavaRohit sharmaView Answer on Stackoverflow
Solution 5 - JavaOhad DanView Answer on Stackoverflow
Solution 6 - JavaTom Hawtin - tacklineView Answer on Stackoverflow