我有一个非常基本的Spring Boot
应用JAR
暴露 API
。
我想做的就是开始JAR
使用以下代码以编程方式。
问题是我没有看到任何输出或异常,但 JAR 没有启动。我尝试将端口更改为尚未绑定(bind)的端口,但仍然无法工作。
但是,当我手动进入cmd
时和cd
进入C:\LDC\dev-server
目录并执行 java -jar todo-rest-app-0.0.1-SNAPSHOT.jar --server.port=8081
应用程序启动,我可以使用 http://localhost:8080/todos
访问 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
最佳答案
基于 SO 链接 Execute .jar file from a Java program由 @Sabmit 提供,我发布了对我有用的解决方案。
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();
}
关于java - 无法通过Java代码执行java -jar命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58644788/