I would like to check whether an existing file is in a specific directory or a subdirectory of that.
I have two File objects.
File dir;
File file;
<
This method looks pretty solid:
/**
* Checks, whether the child directory is a subdirectory of the base
* directory.
*
* @param base the base directory.
* @param child the suspected child directory.
* @return true, if the child is a subdirectory of the base directory.
* @throws IOException if an IOError occured during the test.
*/
public boolean isSubDirectory(File base, File child)
throws IOException {
base = base.getCanonicalFile();
child = child.getCanonicalFile();
File parentFile = child;
while (parentFile != null) {
if (base.equals(parentFile)) {
return true;
}
parentFile = parentFile.getParentFile();
}
return false;
}
Source
It is similar to the solution by dacwe but doesn't use recursion (though that shouldn't make a big difference in this case).