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;
<
In addition to the asnwer from rocketboy, use getCanonicalPath()
instad of getAbsolutePath()
so \dir\dir2\..\file
is 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);
Do not forget to catch any Exception
with try {...} catch {...}
.
NOTE: You can use FileSystem.getSeparator()
instead of File.separator
. The 'correct' way of doing this will be to get the getCanonicalPath()
of the directory that you are going to check against as a String
, then check if ends with a File.separator
and if not then add File.separator
to the end of that String
, to avoid double slashes. This way you skip future odd behaviours if Java decides to return directories with a slash in the end or if your directory string comes from somewhere else than Java.io.File
.
NOTE2: Thanx to @david for pointing the File.separator
problem.