Parent Parent Directory in Java

Please explain to me why when I run this code everything is fine and I get the 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("..//.."); anyway i have null in dirUrl.

How can I get the parent / parent / parent directory in Java?

+4
source share
2 answers

NOTICE :

  • As noted earlier, using any function when retrieving any parent directory is a very bad design idea (and one that almost certainly fails).
  • If you provide more detailed information about what you are trying to achieve (the big picture), someone can probably offer a better solution.

However, you can 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 technique may work in your development environment, but may (and probably will) produce unexpected results when your application is β€œcorrectly” deployed.

+12
source

The result you get is absolutely right.

I think you misunderstood the use of class.getResource .

Suppose you have the package com.test and MyClass inside this package.

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

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

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

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

So, class.getResource will not exit a specific package structure and begin accessing your computer directory. Here's how it doesn't work. This is done only in the structure of the current class .

+4
source

Source: https://habr.com/ru/post/1482934/


All Articles