In addition to rocketboy's asnwer, use getCanonicalPath() instad getAbsolutePath() , so \dir\dir2\..\file converted to \dir\file :
boolean areRelated = file.getCanonicalPath().contains(dir.getCanonicalPath() + File.separator); System.out.println(areRelated);
or
boolean areRelated = child.getCanonicalPath().startsWith(parent.getCanonicalPath() + File.separator);
Remember to catch Exception with try {...} catch {...} .
NOTE. You can use FileSystem.getSeparator() instead of File.separator . The βrightβ way to do this is to get getCanonicalPath() directory that you are going to check as String , and then check to see if it ends with File.separator , and if not, add File.separator to the end of this String to avoid double slashes. This way you skip future odd behavior if Java decides to return the slash directories at the end or if your directory line comes from somewhere else than Java.io.File .
NOTE2: Thanx to @david to indicate File.separator problem.
Jorge fuentes gonzΓ‘lez
source share