Parent parent directory in Java

2019-01-11 20:59发布

问题:

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?

回答1:

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.



回答2:

The result you are getting is perfectly right.

I think you have misunderstood the use of class.getResource.

Lets say you have package com.test and MyClass inside this package.

This MyClass.class.getResource(".") will give you the location of the file you are executing from. Means location of MyClass.

This MyClass.class.getResource("..") will go 1 level up in your package structure. So, this will return the location of directory test.

This MyClass.class.getResource("../..") will go further 1 level up. So, this will return the location of directory com.

Now, this MyClass.class.getResource("../../..") will attempt to go further 1 level up but since there is no package directory exists, this will return null.

So, class.getResource will not go out of the defined package structure and start accessing your computer directory. This is how this does not work. This only searches within your current class package structure.