Skip to content

Instantly share code, notes, and snippets.

@SergKolo
Forked from KazWolfe/Recurse.java
Created January 24, 2017 00:40
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 SergKolo/8f8215b7f1ac6a505e6b8fb3ef4909db to your computer and use it in GitHub Desktop.
Save SergKolo/8f8215b7f1ac6a505e6b8fb3ef4909db to your computer and use it in GitHub Desktop.
Recursively list directories/files through Java
/*
* Recursively list directories/files through Java, akin to Linux's `ls -R` command.
* (c) 2017, KazWolfe. Under MIT license.
*
* To use, save to `Recurse.java` and compile with `javac Recurse.java`.
* Run with `java -cp . Recurse /path/to/operate/on`. Be sure you are passing in a folder.
*/
import java.io.File;
import java.lang.String;
class Recurse {
public static void main(String[] args) {
// Call the recursive method.
recursivelyList(new File(args[0]));
}
public static void recursivelyList(File folder) {
File[] fileList = folder.listFiles();
String[] fileNames = new String[fileList.length];
// Get pretty names for printing.
for (int i = 0; i < fileList.length; i++) {
fileNames[i] = fileList[i].getName();
}
System.out.println(folder.getPath() + ":\n" + String.join(" ", fileNames));
// Iterate through and call this function for any sub-directories.
for (File f2 : fileList) {
if (f2.isDirectory()) {
System.out.println("");
recursivelyList(f2);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment