For a program I’m trying to create a directory tree. So the first part of my program uses Paths to traverse the directory I need:
public static void main(String[] args) throws IOException {
Path startingDir = Paths.get("/home/somedirectory");
PrintFiles pf = new PrintFiles();
Files.walkFileTree(startingDir, pf);
}
And the PrintFiles program (I directly copied this from the guide on how to use paths for walking a tree) http://download.oracle.com/javase/tutorial/essential/io/walk.html:
public static class PrintFiles extends SimpleFileVisitor<Path> {
//Print information about each type of file.
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
if (attr.isSymbolicLink()) {
System.out.format("Symbolic link: %s ", file);
} else if (attr.isRegularFile()) {
System.out.format("Regular file: %s ", file);
} else {
System.out.format("Other: %s ", file);
}
System.out.println("(" + attr.size() + "bytes)");
return CONTINUE;
}
//Print each directory visited.
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
System.out.format("Directory: %s%n", dir);
return CONTINUE;
}
public FileVisitResult visitFileFailed(Path file, IOException exc) {
System.err.println(exc);
return CONTINUE;
}
}
I also have a generic tree program that creates a tree with any number of nodes, with the typical add nodes remove nodes etc functions (I’m not going to post the code because its long and I don’t think its really necessary since its a pretty standard implementation).
My question is how exactly do I do something where I can create a generic tree that represents the directory tree for my specific directory? I’m not exactly familiar with how the Path and File libraries work.
Thanks,
Kevin
You’ll need to implement
preVisitDirectory, postVisitDirectory and visitFile. And you’ll need to hold the “current node” in your visit implementation.currentNodeand then setcurrentNode = newNodecurrentNodecurrentNode = currentNode.getParent()So sort of like a stack operation where you “push” in
preVisitand “pop” inpostVisit.