Last active
August 31, 2021 08:44
-
-
Save charlesreid1/50928a0f0bf17bf360fb9234fd77756a to your computer and use it in GitHub Desktop.
Recursion: Directory Crawl Example with Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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