Skip to content

Instantly share code, notes, and snippets.

@charlesreid1
Last active August 31, 2021 08:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlesreid1/50928a0f0bf17bf360fb9234fd77756a to your computer and use it in GitHub Desktop.
Save charlesreid1/50928a0f0bf17bf360fb9234fd77756a to your computer and use it in GitHub Desktop.
Recursion: Directory Crawl Example with Java
import java.io.*;
public class Directory {
private static void crawl(File f, int indent) {
// Always print the name of the File object, with appropriate indentation
for(int i=0; i<4*indent; i++) {
System.out.print(" ");
}
System.out.println(f.getName());
// Recursive case: is directory
if(f.isDirectory()) {
File[] files = f.listFiles();
for(File tempfile : files) {
crawl(tempfile, indent+1);
}
}
// Base case: file (return nothing)
}
public static void crawl(File f) {
// This public method hides the "indentation" detail from the user
crawl(f,0);
}
public static void main(String[] args) {
crawl(new File("/temp"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment