How can I get a tree of all the files from a current folder in 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.
Check out Apache Commons FileUtils (listFiles, iterateFiles, etc.). Nice convenience methods for doing what you want and also applying filters.
http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html
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 listFiles() returns null for non-directories.
public static void main(String[] args) {
final Collection<File> all = new ArrayList<File>();
addFilesRecursively(new File("."), all);
System.out.println(all);
}
private static void addFilesRecursively(File file, Collection<File> all) {
final File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
all.add(child);
addFilesRecursively(child, all);
}
}
}
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.
You can also use the FileFilter
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();
}});
}
}