Start an external command line process in Java 11

1.1k Views Asked by At

I am using a CLI based validation tool to check some image files. It runs on command prompt where commands are like "my_app input_file config_file". I want to integrate it in a Java application (in Java 11). So i need to run them from my Java project. I tried to start the application from Java by following code :

Runtime rt = Runtime.getRuntime();
        try {
            rt.exec(new String[]{"/path/to/external/application/exefile","/c","./my_command -h"});

        } catch (IOException e) {
            e.printStackTrace();
        }

But it does not prompt the command line and start the application. Could anyone tell me how to run the process in Java 11 ?

Update:

My external process is working now. But i got another problem. The process returns some output which i need to check line by line. i need to check whether it shows any invalid errors. in case of invalid errors, i will call another external process. i was trying to use BufferedReader to process the output like below, but it does not show any result.

            BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));

String s = null;
            while ((s = output.readLine()) != null) {
                System.out.println(s);
            }
1

There are 1 best solutions below

10
On BEST ANSWER

Mind the documentation of Runtime.exec(…):

An invocation of the form exec(cmdarray) behaves in exactly the same way as the invocation exec(cmdarray, null, null).

exec(cmdarray, null, null):


ProcessBuilder.start() is now the preferred way to start a process with a modified environment.

The problem is that exec always creates pipes for the standard I/O that your process must read or write, to communicate with the new process. Only ProcessBuilder allows to alter that behavior in the intended way:

Process p = new ProcessBuilder(
    "/path/to/external/application/exefile", "/c", "./my_command -h")
    .inheritIO().start();

The crucial part is inheritIO(), to tell the process builder that the new process should inherit the standard input, output, and error channels, instead of creating pipes, to use the same console as your process.