Getting filesystem path of class being executed [duplicate]

天大地大妈咪最大 提交于 2019-11-26 05:25:30

问题


Is there any way to determine current filesystem location of executed class from the code of this class, in runtime, given that it\'s executed using java command?

For example for following class:

public class MyClass{
 public static void main(String[] args){\\
   new MyClass().doStuff();
 }

 private void doStufF(){
   String path = ... // what to do here?!
   System.out.println(\"Path of class being invoked: \" + path);
 }

}

Is there any way to get and print the correct path in filesystem of MyClass.class file just being invoked?

Similarly, if I invoke jar file from java -jar command, is there any way to get a path of jar file from within classes inside that jar?

P.S.:Please, do not make any assumptions about working directory from which java command is invoked!


回答1:


The following code snippet will do this for you:

final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

replace MyClass with your main class

The resulting File object f represents the .jar file that was executed. You can use this object to get the parent to find the directory that the .jar is in.



来源:https://stackoverflow.com/questions/11747833/getting-filesystem-path-of-class-being-executed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!