Javaコードからjarファイル名を確認したいと思います。私はGoogleで多くのソリューションを見つけましたが、何も動作しません。私がここで何を試してみたかは、多数のソリューションが掲載されているスタックオーバーフローフォーラムです:stackoverflowJarファイル名形式javaコード
私は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ファイルにあるクラスに入れたいと思います。
編集3:
4文字の単語がある:私もこのコードを試してみました :
File file = null;
try {
System.out.println(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
編集4:私はこれを得た方法rsrc:./
コード
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
このコードは完全に日食で実行されますが、私は実行可能なjarファイルを作成するとき、私はあなたが問題を見ることができると思います。
投稿したリンクにはいくつか解決策があります。あなたは「何も働かない」と言います - なぜ彼らが働かないのかを詳しく説明できますか? – EboMike
JARファイル名は* * *ですか? – bmargulies
編集後、私は質問が-1に値するとは思わない。 – EboMike