click below
click below
Normal Size Small Size show me how
OCPJP708.4
Cert Obj Recursively access a directory tree
[8.4.1] Objective | Recursively access a directory tree using the DirectoryStream and FileVisitor interfaces. |
[8.4.2] To list out all the users with a home directory on this computer. | DirectoryStream<Path> stream = // use try with resources Files.newDirectoryStream(dir)) |
[8.4.3]There is one limitation with DirectoryStream. It can only look at one directory. | One way to remember this is that it works like the dir command in DOS or the ls command in UNIX. Or you can remember that DirectoryStream streams one directory. |
[8.4.4] There are two parameters to visitFile(). | The first one is the Path object representing the current file. The other is a BasicFileAttributes interface. Lets you find out if the current file is a directory, when it was created, and many other similar pieces of data. |
[8.4.5] Depth-first search | Note that Java goes down as deep as it can before returning back up the tree. This is called a depth-first search. We said "might" because files and directories at the same level can get visited in either order. |
[8.4.6] preVisitDirectory | Called before drilling down into the directory |
[8.4.7] visitFile | Called once for each file (but not for directories) |
[8.4.8] visitFileFailed | Called only if there was an error accessing a file, usually a permissions issue |
[8.4.9] postVisitDirectory | Called when finished with the directory on the way back up |