我正在为我构建的jar构建一个包装jar.它将处理更新主应用程序并确保用户是有效用户.我有一个重大问题,因为我无法使外部jar启动功能正常工作.这是我到目前为止:
ProcessBuilder builder = new ProcessBuilder("java -jar ~/Documents.Java/myJar.jar"); try { Process process = builder.start(); } catch (Exception e) { e.printStackTrace(); }
但是,我只是得到一个文件未找到异常.
java.io.IOException: Cannot run program "java -jar ~/Documents/Java/myJar.jar": error=2,No such file or directory at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048) at com.mycompany.DHSLauncher.Launcher.lambda$4(Launcher.java:109) at java.util.Optional.ifPresent(Optional.java:159) at com.mycompany.DHSLauncher.Launcher.showLogin(Launcher.java:102) at com.mycompany.DHSLauncher.Launcher.start(Launcher.java:35) at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863) at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326) at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295) at java.security.AccessController.doPrivileged(Native Method) at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294) at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95) Caused by: java.io.IOException: error=2,No such file or directory at java.lang.UNIXProcess.forkAndExec(Native Method) at java.lang.UNIXProcess.<init>(UNIXProcess.java:248) at java.lang.ProcessImpl.start(ProcessImpl.java:134) at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029) ... 10 more
如果我复制java -jar~ / Documents.Java / myJar.jar并将其粘贴到终端,它就可以运行并启动jar.我不知道这里发生了什么.该路径应该是相对于正在运行的jar的位置吗?
解决方法
靠近dupe
Java execute process on linux和
Difference between ProcessBuilder and Runtime.exec()
除了关于波浪号(非)扩展的正确点之外,您还将整个命令行作为一个参数传递给新的ProcesssBuilder.与Runtime.exec()不同,Runtime.exec()将单个String视为一种特殊情况,并且大多数(但不完全)像典型的Unix shell一样拆分为以空格分隔的标记,ProcessBuilder ctor不会这样做.这可以在您发布的回溯开始时的异常消息中看到.您需要单独的参数,例如:
ProcessBuilder builder = new ProcessBuilder("java","-jar",System.getProperty("user.home")+"/Documents.Java/myJar.jar"); // three String's passed to vararg,compiler makes array for you
或者可能(但我不推荐)
String line = "java -jar " + System.getProperty("user.home")+"/Documents.Java/myJar.jar"; ProcessBuilder builder = new ProcessBuilder( line.split(" ") ); // array of three String's passed directly to vararg