Skip to content

Instantly share code, notes, and snippets.

@ramonaharrison
Created November 15, 2015 16:24
Show Gist options
  • Save ramonaharrison/9c28875377844dbe3419 to your computer and use it in GitHub Desktop.
Save ramonaharrison/9c28875377844dbe3419 to your computer and use it in GitHub Desktop.
Tree HW
package nyc.c4q.ramonaharrison;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import static java.nio.file.FileVisitResult.*;
public class Tree {
public static void main(String[] args) {
Path startingDir = new File(".").toPath();
PrintFiles pf = new PrintFiles();
try {
Files.walkFileTree(startingDir, pf);
} catch (IOException e) {
e.printStackTrace();
}
}
public static class PrintFiles extends SimpleFileVisitor<Path> {
public String indent = "";
// Print each file visited.
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attr) {
System.out.println("│" + indent + "└──" + file);
return CONTINUE;
}
// Print each directory visited.
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs) {
System.out.println("│" + indent + "└──" + dir);
indent = " " + indent;
return CONTINUE;
}
// Print each directory visited.
@Override
public FileVisitResult postVisitDirectory(Path dir,
IOException exc) {
indent = indent.substring(4);
return CONTINUE;
}
// If there is some error accessing the file, let the user know.
@Override
public FileVisitResult visitFileFailed(Path file,
IOException exc) {
System.err.println(exc);
return CONTINUE;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment