Java: How to check if a directory is inside other directory

Ond*_*žka 2 java filesystems path

How can I check if a given file is under other file?

I.e. 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.

我可以找出一些基于字符串的比较,例如path.toFile().getAbsolutePath().startsWith(path2.toFile().getAbsolutePath()),但这看起来很脆弱而且不对。

Ond*_*žka 6

我找到了这个有用的Path.startsWith( Path other )方法,所以这对我有用:

inputPath.toAbsolutePath().startsWith(outputDirectory.toAbsolutePath())
Run Code Online (Sandbox Code Playgroud)