0

I have a very basic Spring Boot application JAR that exposes an API. All I want to do is start that JAR programatically using the following code.

The problem is that I don't see any output or exceptions but JAR does not start. I tried changing the port to something that is not already bound but still won't work.

However, when I manually go into cmd and cd into C:\LDC\dev-server directory and execute java -jar todo-rest-app-0.0.1-SNAPSHOT.jar --server.port=8081 the application starts and I am able to hit the API with http://localhost:8080/todos url.

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));
    }

}

Output:

jarName: C:\LDC\dev-server\todo-rest-app-0.0.4-SNAPSHOT.jar
Process finished with exit code -1
Nital
  • 5,784
  • 26
  • 103
  • 195
  • I'm confused with your jarname. In your output you have `I:\LDC` but in your code you specify `C:\\LDC...` is this right? – IsThisJavascript Oct 31 '19 at 13:55
  • 2
    The problem is caused because running through Runtime.exec doesn't "load"/doesn't know about all your system settings. You need to provide the full path to java. Alternatively, you can run cmd from Runtime, and then pipe in your commands. – ControlAltDel Oct 31 '19 at 13:57
  • 1
    @IsThisJavascript - Apologize for the typo. It is C:. Edited my question to reflect the correct drive. – Nital Oct 31 '19 at 14:04
  • @Sambit - That is definitely what I was looking for. Thanks ! – Nital Oct 31 '19 at 14:11

1 Answers1

1

Based on the SO link Execute .jar file from a Java program provided by @Sabmit, I am posting the solution that worked for me.

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();
}
Nital
  • 5,784
  • 26
  • 103
  • 195