Parent parent directory in Java

后端 未结 2 1176
臣服心动
臣服心动 2020-12-10 00:19

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(\"..\");


        
相关标签:
2条回答
  • 2020-12-10 00:23

    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.

    0 讨论(0)
  • 2020-12-10 00:48

    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.

    0 讨论(0)
提交回复
热议问题