简体   繁体   中英

Endless loop while using Files.walkFileTree with FOLLOW_LINK on

By using the method Files.walkFileTree(Path, Set<FileVisitOption>, int, FileVisitor) with FileVisitOption.FOLLOW_LINKS on. I get an endless loop with symbolic links redirecting to parent directory.. This java tutorial explains a way how to detect the particular symbolic link causing the issue with the following instructions:

The visitFile method is invoked for files. If you have specified the FOLLOW_LINKS option and your file tree has a circular link to a parent directory, the looping directory is reported in the visitFileFailed method with the FileSystemLoopException . The following code snippet shows how to catch a circular link and is from the Copy example:

@Override
public FileVisitResult
    visitFileFailed(Path file,
        IOException exc) {
    if (exc instanceof FileSystemLoopException) {
        System.err.println("cycle detected: " + file);
    } else {
        System.err.format("Unable to copy:" + " %s: %s%n", file, exc);
    }
    return CONTINUE;
}

It works, it detects the particular file.. However the endless loop remains. How could I proceed to skip only the Symbolic links creating the issue in order to explore the whole FileTree without ending up in an endless loop?

In the example above you return FileVisitResult.CONTINUE . The javadoc says there are three other values in this enum: SKIP_SIBLINGS , SKIP_SUBTREE and TERMINATE . You could try to use one of them whatever is best for your situation.

When walking the file tree with FOLLOW_LINKS and a symbolic link is encountered which would cause a loop back to an ancestor directory:

  • neither preVisitDirectory or postVisitDirectory will be called for the link
  • only visitFileFailed will be called for the link
  • the link will not be followed

As you can see, the file tree walker logic already prevents infinite recursion of this type, and therefore nothing is necessarily wrong with simply logging an error message.

However, something else must be causing the infinite loop in your program. Perhaps you have created a circular reference in your filesystem using hard links?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM