Search code examples
javaexecution

Java - How to execute a process


I'm looking for all the different functions available in JAVA to execute a process/os command.

For example, I familiar with exec('command').

In PHP I familiar with the following functions:

exec()
shell_exec()
system()
passthru()
escapeshellcmd()
backticks (``)
popen()
automatic()

Could you please name the other functions/techniques?


Solution

  • Fortunately, there's a fairly straightforward approach from the JDK: the ProcessBuilder API.

    Here is a thorough example of its implementation. If you don't feel like reading through that, this is a terse example:

    package com.process;
    
    import java.io.File;
    import java.io.IOException;
    import java.lang.ProcessBuilder.Redirect;
    
    public class ProcessBuilder {
        public static void main(String... args) throws IOException, InterruptedException {
            ProcessBuilder builder = new ProcessBuilder("D:/test.bat", "firstArg", "secondArg");
            processBuilder.directory(new File("D:/"));
            File log = new File("D:/log.txt");
            builder.redirectErrorStream(true);
            builder.redirectOutput(Redirect.appendTo(log));
            Process p = builder.start();
            p.waitFor();
        }
    }