Skip to content

Instantly share code, notes, and snippets.

@Sneppys
Created September 28, 2018 22:20
Show Gist options
  • Save Sneppys/b0c1cbd19f1d6ed6db542de72dcf1842 to your computer and use it in GitHub Desktop.
Save Sneppys/b0c1cbd19f1d6ed6db542de72dcf1842 to your computer and use it in GitHub Desktop.
Java method to list all files inside a directory, and print out with indentation.
public static void walkDirectory(File file) {
int levels = file.getAbsolutePath().length() - file.getAbsolutePath().replace(File.separator, "").length();
try {
Files.walk(file.toPath()).map(Path::toFile).forEach((File f) -> {
int subLevels = f.getAbsolutePath().length() - f.getAbsolutePath().replace(File.separator, "").length()
- levels;
String indent = new String(new char[(subLevels) * 4]).replace('\0', ' ');
System.out.println(indent + f.getName() + (f.isDirectory() ? ":" : ""));
});
} catch (IOException e) {
e.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment