[英]Why can't I access a file within my jar unless I'm in the folder with the Jar when I run it?
I recently created an application and successfully jarred this to c:/my/folder/app.jar. 我最近创建了一个应用程序,并将其成功地添加到c:/my/folder/app.jar。 It works like a charm in the following case [Startup #1]:
在以下情况下[启动#1],它的工作原理像一种魅力:
But when I do this, it doesn't work [Startup #2]: 但是当我这样做时,它不起作用[启动#2]:
Because app.jar contains a .exe-file which I try to run in my application: 因为app.jar包含一个.exe文件,我试图在我的应用程序中运行它:
final Process p = Runtime.getRuntime().exec("rybka.exe");
It won't work in example 2 because it can't find the file rybka.exe. 由于找不到文件rybka.exe,因此无法在示例2中运行。
Any suggestions? 有什么建议么?
Something like this is a better way forward. 这样的事情是更好的前进方式。 Copy the exe out of the jar to a temp location and run it from there.
将exe从jar中复制到临时位置,然后从那里运行它。 Your jar will then also be executable via webstart and so on:
然后,您的jar也可以通过webstart等执行:
InputStream src = MyClass.class.getResource("rybka.exe").openStream();
File exeTempFile = File.createTempFile("rybka", ".exe");
FileOutputStream out = new FileOutputStream(exeTempFile);
byte[] temp = new byte[32768];
int rc;
while((rc = src.read(temp)) > 0)
out.write(temp, 0, rc);
src.close();
out.close();
exeTempFile.deleteOnExit();
Runtime.getRuntime().exec(exeTempFile.toString());
If the jar will always be in that directory you can use a full path /my/folder/rybka.exe
. 如果jar始终位于该目录中,则可以使用完整路径
/my/folder/rybka.exe
。 If not, you can use getClass().getProtectionDomain().getCodeSource().getLocation()
to find out the location of the jar and prepend that onto rybka.exe
. 如果不是,则可以使用
getClass().getProtectionDomain().getCodeSource().getLocation()
来找出jar的位置,并将其放在rybka.exe
。
Try extracting the exe to 尝试将exe解压缩到
System.getProperty("java.io.tmpdir"));
then run it from this location too should work every time. 然后从该位置运行它也应该每次都能工作。
Paul 保罗
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.