为什么我无法访问 jar 中的文件,除非运行 Jar 时我位于包含该 Jar 的文件夹中?
我最近创建了一个应用程序并成功将其 jar 到 c:/my/folder/app.jar。 在以下情况下它就像一个魅力[启动#1]:
- 打开cmd
- cd到c:/ my/folder
- java -jar app.jar
但是当我这样做时,它不起作用[启动#2]:
- 打开cmd
- cd 到 c:/my/
- java -jar 文件夹/app.jar
因为 app.jar 包含一个 .exe 文件,我尝试在我的应用程序中运行该文件:
final Process p = Runtime.getRuntime().exec(" rybka.exe");
它在示例 2 中不起作用,因为它找不到文件 rybka.exe。
有什么建议么?
I recently created an application and successfully jarred this to c:/my/folder/app.jar. It works like a charm in the following case [Startup #1]:
- Open cmd
- cd to c:/my/folder
- java -jar app.jar
But when I do this, it doesn't work [Startup #2]:
- Open cmd
- cd to c:/my/
- java -jar folder/app.jar
Because app.jar contains a .exe-file which I try to run in my application:
final Process p = Runtime.getRuntime().exec("rybka.exe");
It won't work in example 2 because it can't find the file rybka.exe.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果 jar 始终位于该目录中,您可以使用完整路径
/my/folder/rybka.exe
。 如果没有,您可以使用 getClass().getProtectionDomain().getCodeSource().getLocation() 找出 jar 的位置并将其添加到 rybka.exe 前面。If the jar will always be in that directory you can use a full path
/my/folder/rybka.exe
. If not, you can usegetClass().getProtectionDomain().getCodeSource().getLocation()
to find out the location of the jar and prepend that ontorybka.exe
.像这样的事情是更好的前进方向。 将 exe 从 jar 复制到临时位置并从那里运行它。 然后,您的 jar 也可以通过 webstart 等执行:
Something like this is a better way forward. Copy the exe out of the jar to a temp location and run it from there. Your jar will then also be executable via webstart and so on:
尝试提取 exe,然后
从该位置运行它,每次也应该有效。
保罗
Try extracting the exe to
then run it from this location too should work every time.
Paul