Reputation: 6624
How can I go about getting the parent directory of a directory?
File parent = new File("");
System.out.println("Parent directory : " + parent.getParent());
prints Parent directory : null
I have a Maven multi-module project and would like to go to the parent folder then get back into each of the module folders and sub-folders getting all the jars in them.
parent
distributor
src.controllers
Dist.java
module1
src.controllers
1App.java
target
module1-1.0-SNAPSHOT.jar-
module2
src.controllers
2App.java
target
module2-1.0-SNAPSHOT.jar-
Above, I wold get from Dist.java to parent then into module1 and module2
Upvotes: 2
Views: 9914
Reputation: 159096
Quoting javadoc of File.getParent()
(emphasis mine):
Returns the pathname string of this abstract pathname's parent, or
null
if this pathname does not name a parent directory.The parent of an abstract pathname consists of the pathname's prefix, if any, and each name in the pathname's name sequence except for the last. If the name sequence is empty then the pathname does not name a parent directory.
Remember, a File
object represent the path string, not an actual file on the file system. The string ""
does not have a parent. The string "a/b/c"
has "a/b"
as the parent, even if they don't physically exist.
So, first you have to resolve the path ""
to a real path by calling getCanonicalFile()
. Then you can find the parent directory.
File file = new File("").getCanonicalFile();
System.out.println("Parent directory : " + file.getParent());
Upvotes: 8