我想从我的java代码中确定jar文件名。我在谷歌找到了很多解决方案,但没有任何效果。只是看到我在这里尝试的是一个stackoverflow论坛,其中发布了一堆解决方案:stackoverflowjar文件名形式的java代码
我有Mac OS X 10.6.5。
当我键入Java的版本我得到这样的结果:
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路径时,某些解决方案会给我“空”值,并且在我想创建文件的实例时也会失败。
其他解决方案,当我要求的路径,他们不给file:/.....
,而是他们给rsch:/
或类似的东西,这我不知道确切,但它是一个4字符的简单单词。
编辑2: 我从控制台运行可执行jar。我想在执行的jar文件中的类中有这个jar文件名。
编辑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文件我想你可以看到这个问题。
您发布的链接提供了一些解决方案。你说“没有任何工作” - 你能详细说明为什么他们不工作? – EboMike 2010-11-27 23:38:31
Jar文件名* what *? – bmargulies 2010-11-27 23:42:41