我想从我的 java 代码中确定 jar 文件名。我在谷歌中找到了很多解决方案,但没有任何效果。只是为了看看我在这里尝试了什么,这是一个 stackoverflow 论坛,其中发布了一堆解决方案:堆栈溢出 https://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file
我有 Mac OS X 10.6.5。
当我输入 java -version 时,我得到以下结果:
java version "1.6.0_22"
Java(TM) SE Runtime Environment (build 1.6.0_22-b04-307-10M3261)
Java HotSpot(TM) 64-Bit Server VM (build 17.1-b03-307, mixed mode)
感谢您的帮助。
编辑:
我编辑我的帖子来回答评论。
当我想要 System.out.println 路径时,某些解决方案给我“null”值,并且当我想要创建文件实例时也会失败。
当我询问路径时,其他解决方案他们没有给出类似的东西file:/.....
,相反,他们给出了类似的东西rsch:/
或者类似的东西,我不太清楚,但它是一个 4 个字符的简单单词。
编辑2:
我从控制台运行一个可执行的 jar。我希望在执行的 jar 文件中的类中包含此 jar 文件名。
Edit 3:
4个字符的单词是:rsrc:./
代码我是如何得到这个的:
File file = null;
try {
System.out.println(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
编辑4:
我也尝试过这段代码:
package core;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class MyClass {
public String getText(String key) {
String path = "" + MyClass.class.getResource("../any.properties");
File file = new File((path).substring(5, path.length()));
Properties props = readProps(file);
return props.getProperty(key);
}
private Properties readProps(File file) {
Properties props = new Properties();
InputStream in = null;
try {
in = new FileInputStream(file);
props.load(in);
in.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return props;
}
public static void main(String[] args) {
System.out.println(new MyClass().getText("anything"));
}
}
得到这个结果:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1937)
at core.PropHandler.getText(MyClass.java:14)
at core.PropHandler.main(MyClass.java:39)
... 5 more
这段代码在 eclipse 中完美运行,但是当我创建可运行的 jar 文件时,我想你可以看到问题。