//Java/JavaTutorials/PrintDirectoryTree.java //Matthew Ellison // Created: 01-07-2020 //Modified: 01-07-2020 //This class will step through a directory and print out the contents //TODO: I am still learning what exactly this code does. I need to insert some comments as soon as I learn what everything is doing. import java.util.EnumSet; import java.io.*; import java.nio.file.*; import java.nio.file.attribute.*; import static java.nio.file.FileVisitResult.*; public class PrintDirectoryTree{ public static void main(String[] args) throws IOException{ String searchDirectory = ""; //This string holds the directory that will be printed //This makes sure something is set for the directory if(args.length == 1){ //Set the argument as the directory searchDirectory = args[0]; } else if(args.length == 0){ //Set the entire C drive as the directory if none was given searchDirectory = "C:/"; } else{ //Print an error and exit if there are mutliple arguments sent System.out.print("There are too many parameters!"); return; } try{ Path startingDir = Paths.get(searchDirectory); EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS); PrintTree pf = new PrintTree(); Files.walkFileTree(startingDir, opts, Integer.MAX_VALUE, pf); } catch(Exception x){ System.err.print("Exception raised: " + x); } } public static class PrintTree extends SimpleFileVisitor{ @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attr){ //This prints out a particular string when a certain type of file is found if(attr.isSymbolicLink()){ System.out.format("Symbolic Link: %s", file); } else if(attr.isRegularFile()){ System.out.format("Real File: %s", file); } else{ System.out.format("Other: %s", file); } //This prints out the size of any given file System.out.println("(" + attr.size() + " bytes)"); return CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs){ //This simply prints out the name of the directory System.out.format("Directory: %s\n", dir); return CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc){ //This prints out whatever error message was thrown System.err.println(exc); return CONTINUE; } } }