Determine if a directory contains a file
I have java.io.File
objects A and B, where A represents a directory and B represents a file. B can be an absolute path or a relative path that is 0 or more levels below A. what's the most effi开发者_如何学JAVAcient way to determine if B is contained by A?
For example,
A is C:\Users\bill\Desktop\abc\xyz123 and B is C:\Users\bob\Documents\inc\data.inc
or
A is C:\Users\bill\Desktop\abc\xyz123 and B is C:\Users\bob\Documents\x1\y1\inc\data.inc
or
A is C:\Users\bill\Desktop\abc\xyz123 and B is ..\..\..\Documents\inc\data.inc
You can check to see if A is the parent of B by doing
A.equals(B.getParentFile())
Edit: If you want to check if B is one or more levels below A, just keep getting the ParentFile until it's A or null
File C = B.getParentFile();
while(C != null) {
if(A.equals(C))
return true;
C = C.getParentFile();
}
return false;
getParentFile()
, which returns the parent directory, and getCanonicalFile()
can be of use. Like so:
File bDir = b.getParentFile();
boolean same = bDir.equals(a) || bDir.getCanonicalFile().equals(a.getCanonicalFile());
Paths can be tricky. If you're lucky the just getParent()
is all that's necessary. Using getCanonicalFile()
should cover the more complicated cases.
Use the class FileUtils:
public static boolean directoryContains(File directory,
File child)
throws IOException
Determines whether the parent directory contains the child element (a file or directory).
精彩评论