Limiting Traversal by Depth Specification – Java I/O: Part II

Limiting Traversal by Depth Specification

The walk() method at (4) in Example 21.5 is called multiple times in the for(;;) loop at (3). From the output, we can see that, for each value of the loop variable depth, the walk() method starts the traversal at the directory a and descends to the depth level given by the loop variable depth. For example, when the value of the depth variable is 3, traversal descends from depth level 0 to depth level 3.

If the constant FileVisitOption.FOLLOW_LINKS is not specified, so that symbolic links are not followed, the traversal will only go as far as the minimum of the maximum depth of the hierarchy and any specified depth level.

Specifying the depth level can result in a more efficient search if it is known that the result is at an approximate depth level, thus avoiding useless searching farther down in the hierarchy.

Handling Symbolic Links

Specifying the constant FileVisitOption.FOLLOW_LINKS in the walk() method call results in symbolic links being followed.

A symbolic link to a file is not a problem, as after visiting the target file, the traversal can continue with the next sibling of the symbolic link.

A symbolic link to a directory that is not a parent directory of the symbolic link is also not a problem, as traversal can continue with the next sibling of the symbolic link, after visiting the target directory.

The problem arises when a symbolic link is to a directory that is a parent directory of the symbolic link. That creates a cyclic path dependency. An example of such a cyclic path dependency is introduced by the symbolic link a/b/c/dir_link to one of its parent directories, a/b, as can be seen in the figure of the directory hierarchy (p. 1347).

When the constant FileVisitOption.FOLLOW_LINKS is specified in the walk() method call, the method detects such cyclic path dependencies by monitoring which entries have been visited. Example 21.5 illustrates this scenario when the constant FileVisitOption.FOLLOW_LINKS is specified and the specified depth is greater than 3. From the output, we can see that, at depth level 4, the method detects that the symbolic link a/b/c/dir_link to its parent directory a/b creates a cyclic path dependency, as the target directory lies on the path to the symbolic link and has been visited before. The method throws a hefty FileSystemLoopException to announce the outcome.

Leave a Reply

Your email address will not be published. Required fields are marked *