[Solved] I’ve already created a Process Builder. How do I run all of the programs in the Process builder?


First, you need to make sure the command you are using actually works at the command. If it does not, then it’s not going to work in Java.

Next, one of the main reasons for using ProcessBuilder is to deals with spaces in the command/parameters better then Runtime#exec.

String command = "/Applications/MiKTeX Console.app/Contents/bin/miktex-pdftex";
String outputDir = System.getProperty("user.dir");
String sourceFile = "Sample.tex";

List<String> commands = new ArrayList<>();
commands.add(command);
commands.add("--interaction=nonstopmode");
commands.add("--output-directory=" + outputDir);
commands.add(sourceFile);

So the above is very simple…

  • The command I want to run is /Applications/MiKTeX Console.app/Contents/bin/miktex-pdftex (I’m running on MacOS and I couldn’t get the command installed outside the application bundle)
  • I want the output-directory to be the same as the current working directory (System.getProperty("user.dir")), but you could supply what every you need
  • I’m running in “nonstopmode” (--interaction=nonstopmode) because otherwise I would be required to provide input, which is just more complex
  • And my input file (Sample.tex) which is also in the working directory.

Next, we build the ProcessBuilder and redirect the error stream into the InputStream, this just reduces the next to read these two streams separately…

ProcessBuilder pb = new ProcessBuilder(commands);
pb.redirectErrorStream(true);

Next, we run the command, read the contents of the InputStream (otherwise you can stall the process), you can do what ever you want with this, I’ve just echoed it to the screen

try {
    Process process = pb.start();
    InputStream is = process.getInputStream();
    int in = -1;
    while ((in = is.read()) != -1) {
        System.out.print((char)in);
    }
    int exitValue = process.waitFor();

    System.out.println("");
    System.out.println("Did exit with " + exitValue);
} catch (IOException | InterruptedException ex) {
    ex.printStackTrace();
}

The use int exitValue = process.waitFor(); here is just to ensure that command has completed and get the exit value it generated. Normally, 0 is success, but you’d need to read the documentation of the command to be sure

1

solved I’ve already created a Process Builder. How do I run all of the programs in the Process builder?