Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parent parent directory in Java

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?

like image 827
Boris Mitioglov Avatar asked May 27 '13 09:05

Boris Mitioglov


People also ask

What is a parent directory?

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.

Where is the parent directory?

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.

What is parent file in java?

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.

What is getParent in java?

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.


1 Answers

NOTICE:

  1. As others have already stated, basing any functionality on the retrieval of some parent directory is a very bad design idea (and one that is almost certain to fail too).
  2. If you share more details about what you are trying to achieve (the big picture), someone could probably propose a better solution.

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.

like image 159
gkalpak Avatar answered Oct 27 '22 01:10

gkalpak