Search code examples
javaprocessbuilder

ProcessBuilder - array parameter


I am running an .exe from a Java application using ProcessBuilder. I can run the .exe, and can pass it scalar arguments, but I was wondering how to pass in an array as a parameter?

My code looks like:

Process process = new ProcessBuilder(path, 
    Integer.toString(firstParam), 
    "where i want array to be").
    start();

Solution

  • When using ProcessBuilder each element in the command is a separate argument.

    String[] array = {"Item 1", "Item 2", "Item 3"};
    String arg = String.join(",", array);
    Process process = new ProcessBuilder("path/to/command.exe", "--argument-name", arg)
                .inheritIO() // replace with your own IO handling if needed
                .start();
    

    I don't believe you have to worry with surrounding arg in quotes since ProcessBuilder will take care of sending it as a single argument for you.

    The above should be equivalent to this command line:

    path/to/command.exe --argument-name "Item 1,Item 2,Item 3"