Please explain me, why when i run this code, all is fine and i get parent directory of my classes:
URL dirUrl = PathsService.class.getResource("..");
and when I run this code:
URL dirUrl = PathsService.class.getResource("../..");
I get null in dirUrl.
I try like this:
URL dirUrl = PathsService.class.getResource("..//..");
all the same I have a null in dirUrl.
How can I get parent/parent/parent ... directory in Java?
In computing terms, a parent directory is a directory that is above another directory. The root directory is the only directory that cannot be put below any other directory. The directory below the parent directory is the subdirectory. The directory path looks like this: root directory/parent directory/subdirectory.
Every directory, except the root directory, lies beneath another directory. The higher directory is called the parent directory, and the lower directory is called a subdirectory.
File getParent() method in Java with Examples The getParent() method is a part of File class. This function returns the Parent of the given file object. The function returns a string object which contains the Parent of the given file object.
getParent. 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.
NOTICE:
That said, you could try the following code:
import java.nio.file.*;
...
Path path = Paths.get(PathsService.class.getResource(".").toURI());
System.out.println(path.getParent()); // <-- Parent directory
System.out.println(path.getParent().getParent()); // <-- Parent of parent directory
Also note, that the above technic may work on your development environment, but may (and probably will) produce unexpected results when your application is "properly" deployed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With