I am trying to find if given path is possible child of another path using java. Both path may not exist.
Say c:\Program Files\My Company\test\My App
is a possible child of c:\Program Files
.
Currently I am doing this with
boolean myCheck(File maybeChild, File possibleParent)
{
return maybeChild.getAbsolutePath().startsWith( possibleParent.getAbsolutePath());
}
Old question but a pre-1.7 solution:
For completeness the java 1.7+ solution:
Asides from the fact the paths may not exist (and the canonicalisation may not succeed), this looks like a reasonable approach that should work in the straightforward case.
You may want to look at calling getParentFile() on the "maybe child" in a loop, testing if it matches the parent at each step. You can also short-circuit the comparison if the parent isn't a (real) directory.
Perhaps something like the following:
Note that if you want the child relationship to be strict (i.e. a directory is not a child of itself) you can change the initial
child
assignment on line 9 to bechild.getParentFile()
so the first check happens on the child's containing directory.That will probably work fine as it is, although I would use
getCanonicalPath()
rather thangetAbsolutePath()
. This should normalize any weird paths likex/../y/z
which would otherwise screw up the matching.This will work for your example. It will also return
true
if the child is a relative path (which is often desirable.)You can also use java.nio.file.Path to do this much more easily. The java.nio.file.Path.startsWith method seems to handle all possible cases.
Example:
outputs
If you need more reliability you can use "toRealPath" instead of "toAbsolutePath".