获取正在执行的类的文件系统路径 [英] Getting filesystem path of class being executed
问题描述
有没有办法在运行时从这个类的代码中确定已执行类的当前文件系统位置,因为它是使用 java
命令执行的?
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?
例如以下课程:
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);
}
}
有没有办法得到和在刚被调用的MyClass.class文件的文件系统中打印正确的路径?
Is there any way to get and print the correct path in filesystem of MyClass.class file just being invoked?
同样,如果我从 java -jar $调用jar文件c $ c>命令,有没有办法从jar内的类中获取jar文件的路径?
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?
PS:请不要做任何关于工作目录的假设,从中调用 java
命令!
P.S.:Please, do not make any assumptions about working directory from which java
command is invoked!
推荐答案
以下代码段将为您执行此操作:
The following code snippet will do this for you:
final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
用您的<替换 MyClass
code> main class
replace MyClass
with your main
class
生成的文件
对象 f
表示已执行的 .jar
文件。您可以使用此对象让父级找到 .jar
所在的目录。
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.
这篇关于获取正在执行的类的文件系统路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!