Java中的父父目录 [英] Parent parent directory in Java
问题描述
URL dirUrl = PathsService.class.getResource(..);
,当我运行这段代码:
URL dirUrl = PathsService.class.getResource(../ ..);
我在dirUrl中获得 null 。
我尝试这样:
URL dirUrl = PathsService.class.getResource(..//..\">;
all相同,我在dirUrl中有一个 null 。
如何在Java中获取父/父/父目录?
通知:
- 如果您分享有关您要实现的更多细节(大图),有人可能会提出更好的解决方案。
<正如其他人已经说过的那样,基于检索某些父目录的任何功能是一个非常糟糕的设计思想(而且几乎肯定也会失败)。
可以这样说,你可以尝试以下代码:
import java.nio.file 。*;
...
路径路径= Paths.get(PathsService.class.getResource(。)。toURI());
System.out.println(path.getParent()); //< - 父目录
System.out.println(path.getParent()。getParent()); //< - 父目录的父母
另请注意,上述技术可能适用于您的开发环境,但是当您的应用程序正确部署时,可能(也可能会)会产生意想不到的结果。
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?
NOTICE:
- 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).
- 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.
这篇关于Java中的父父目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!