【问题标题】:Not able to execute java -jar command through Java code [duplicate]无法通过Java代码执行java -jar命令[重复]
【发布时间】:2020-02-26 21:33:47
【问题描述】:

我有一个非常基本的Spring Boot 应用程序JAR,它公开了一个API。 我要做的就是使用以下代码以编程方式启动JAR。

问题是我没有看到任何输出或异常,但 JAR 没有启动。我尝试将端口更改为尚未绑定但仍无法使用的端口。

但是,当我手动进入cmd 和cd 进入C:\LDC\dev-server 目录并执行java -jar todo-rest-app-0.0.1-SNAPSHOT.jar --server.port=8081 时,应用程序启动,我可以使用http://localhost:8080/todos url 访问API。

Main.java

public class Main {

    public static void main(String[] args) throws IOException, InterruptedException {
        new Main ().executeJar(new File("todo-rest-app-0.0.1-SNAPSHOT.jar"));
    }

    private void executeJar(File artifact) throws IOException, InterruptedException {
        String jarName = "C:\\LDC\\dev-server\\" + artifact.getName();
        System.out.println("jarName: " + jarName);
        Process ps = Runtime.getRuntime().exec("java -jar " + jarName + " --server.port=8081");
        ps.waitFor();
        java.io.InputStream is = ps.getInputStream();
        byte b[] = new byte[is.available()];
        is.read(b, 0, b.length);
        System.out.println(new String(b));
    }

}

输出:

jarName: C:\LDC\dev-server\todo-rest-app-0.0.4-SNAPSHOT.jar
Process finished with exit code -1

【问题讨论】:

  • 我对你的 jarname 感到困惑。在您的输出中您有 I:\LDC 但在您的代码中您指定 C:\\LDC... 是这样吗?
  • 这个问题是因为通过 Runtime.exec 运行不会“加载”/不知道你所有的系统设置。您需要提供 java 的完整路径。或者,您可以从运行时运行 cmd,然后通过管道输入您的命令。
  • @IsThisJavascript - 为错字道歉。是C:。编辑了我的问题以反映正确的驱动器。
  • @Sambit - 这绝对是我想要的。谢谢!

标签: java windows jar executable-jar ps


【解决方案1】:

基于@Sabmit 提供的SO 链接Execute .jar file from a Java program,我发布了对我有用的解决方案。

private void executeJar2(File artifact) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder("C:\\JDK\\1.8.0.181\\bin\\java", "-jar", artifact.getName(), "--server.port=8081");
    pb.directory(new File("C:\\LDC\\dev-server\\"));
    Process p = pb.start();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多