Java Path File Check nio isContained(Path contained, Path container)

Here you can find the source of isContained(Path contained, Path container)

Description

Inspired by <a href="http://stackoverflow.com/questions/18227634/check-if-file-is-in-subdirectory" >http://stackoverflow.com/questions/18227634/check-if-file-is-in-subdirectory</a>

License

Open Source License

Parameter

Parameter Description
contained The path to be checked. This does not need to exist.
container The parent directory. This must exist on the filesystem.

Exception

Parameter Description
IOException If an error occurs or, potentially, if either path does not exist.

Return

If contained is a subfolder of container, true.

Declaration

public static boolean isContained(Path contained, Path container) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;

import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    /**/*  ww  w.  ja v  a  2 s.  c o m*/
     * Inspired by <a href="http://stackoverflow.com/questions/18227634/check-if-file-is-in-subdirectory"
     * >http://stackoverflow.com/questions/18227634/check-if-file-is-in-subdirectory</a>
     *
     * @param contained The path to be checked. This does not need to exist.
     * @param container The parent directory. This must exist on the filesystem.
     * @return If <code>contained</code> is a subfolder of <code>container</code>, true.
     * @throws IOException If an error occurs or, potentially, if either path does not exist.
     */
    public static boolean isContained(Path contained, Path container) throws IOException {
        Path current = contained.normalize();

        // Iterate up the path to see if we find the container path:
        while (current != null) {
            if (Files.isSameFile(container, current)) {
                return true;
            }
            current = current.getParent();
        }

        // If we didn't find the container path
        // amongst the parents of the contained path,
        // this path is not contained:
        return false;
    }
}

Related

  1. isAbsolute(String path)
  2. isAbsolutePath(String path)
  3. isAsciiText(Path p)
  4. isBallerinaProject(Path path)
  5. isBinary(Path file)
  6. isDirectory(Path fileOrDir, LinkOption... options)
  7. isDirectory(Path value)
  8. isDirectoryEmpty(Path dir)
  9. isDirectoryEmpty(Path directory)