Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
760 views
in Technique[技术] by (71.8m points)

file - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...