Search code examples
javapathfilesystems

How to check if a directory is inside other directory


How can I check if a given file is under other file? For example, I have new Paths.get("/foo/bar/") and new Paths.get("./abc/def.jar"). And I want to check whether the second is under /foo/bar.

I can figure out some string based comparisons like path.toFile().getAbsolutePath().startsWith(path2.toFile().getAbsolutePath()), but that looks fragile and not right.


Solution

  • I've found this useful Path.startsWith( Path other ) method, so this worked for me:

    inputPath.toAbsolutePath().startsWith(outputDirectory.toAbsolutePath())