Skip to content

Instantly share code, notes, and snippets.

@andrewnguyen42
Created April 11, 2013 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewnguyen42/5365727 to your computer and use it in GitHub Desktop.
Save andrewnguyen42/5365727 to your computer and use it in GitHub Desktop.
Quick example of file traversal
import java.io.File;
public class FileLister {
public static void main(String[] args) {
list(new File("/"));
}
/**
* Display a list of the specified file and all its descendants.
*/
public static void list(File root) {
// We don't expect the caller to be concerned with the level argument, so
// we make this method just a wrapper method that is called once. We
// call the helper method that does the real work and prime level to be
// 0.
list(root, 0);
}
/**
* Display a list of all files in the file system descending from
* root, one per line. Files are indented according
* to their depth in the hierarchy, as indicated by level.
*
* @param root
* The root file of this hierarchy.
*
* @param level
* The number of levels into the overall hierarchy that we have
* traversed.
*/
private static void list(File root, int level) {
// Print indented filename. This is a bit tricky, but as level
// increases, we print out a space ' ' with increased padding:
// %1c, %2c, %3c, and so on. %s displays the string argument.
// %n turns into a platform-independent newline. Check out the
// Javadoc for formatted printing if you want to know more:
//
// http://java.sun.com/javase/6/docs/api/java/util/Formatter.html#syntax
//
// We could do the same thing with a loop.
System.out.printf("%" + (level + 1) + "c%s%n", ' ', root.getName());
// See if this file is a directory and has any files within it. If
// so, each of those files becomes the root of a hierarchy one level
// deeper.
File[] contents = root.listFiles();
if (contents != null) {
for (int i = 0; i < contents.length; ++i) {
list(contents[i], level + 1);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment