为什么我无法访问 jar 中的文件,除非运行 Jar 时我位于包含该 Jar 的文件夹中?

发布于 2024-08-01 12:40:46 字数 458 浏览 4 评论 0原文

我最近创建了一个应用程序并成功将其 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

墨落成白 2024-08-08 12:40:46

如果 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 use getClass().getProtectionDomain().getCodeSource().getLocation() to find out the location of the jar and prepend that onto rybka.exe.

空宴 2024-08-08 12:40:46

像这样的事情是更好的前进方向。 将 exe 从 jar 复制到临时位置并从那里运行它。 然后,您的 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());

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:

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());
怼怹恏 2024-08-08 12:40:46

尝试提取 exe,然后

System.getProperty("java.io.tmpdir"));

从该位置运行它,每次也应该有效。

保罗

Try extracting the exe to

System.getProperty("java.io.tmpdir"));

then run it from this location too should work every time.

Paul

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文