Java 相对jar执行文件

Java execute file relative to jar

我有一个 c# 控制台应用程序,我将使用 Java 和此处描述的技术 Sending commands to a console application?

发送推荐

我的问题是控制台应用程序位于与 jar 位于同一文件夹中的文件夹中,我无法找到如何相对于与 jar 相同的目录执行文件。

我在 Java 中尝试了很多东西,比如

Process pr = Runtime.getRuntime().exec("runtime_libraries/consoleapp.exe");

但是提示找不到文件。

java.io.IOException: CreateProcess error=2, The system cannot find the file specified

我以为它会很简单,但显然不是。

所以我的问题是,如何将相对路径放入运行时执行程序?

当您遇到此类问题时,您需要做一些初步检查...

  1. 使用 System.out.println(System.getProperty("user.dir")); 验证您当前的 运行 位置,并确保它在您期望的位置;
  2. 使用 System.out.println(new File("runtime_libraries/consoleapp.exe").exists()));
  3. 验证 consoleapp.exe 是否存在

大多数 IDE 允许您在开发过程中更改工作目录。生产时,应确保工作目录设置正确(如Windows下,可在指定位置配置快捷方式为"start")