Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a directory contains a file

Tags:

java

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 efficient 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

like image 932
javacavaj Avatar asked Jan 25 '26 06:01

javacavaj


1 Answers

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;
like image 132
Chris Flynn Avatar answered Jan 27 '26 18:01

Chris Flynn