1

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?

user3146008
  • 37
  • 1
  • 6
  • @hhafeez I don't think he's referring to a Java thread; he's referring to native system processes. E.g., calling `grep` on Linux. – Keith Feb 20 '17 at 17:34
  • Threads are technically light weight processes – hhafeez Feb 20 '17 at 17:36
  • @hhafeez I know that, but it's an apples-to-oranges comparison here. A java thread doesn't freely give you access to a native OS call. The OP is asking for Java's analogs to the system calls specified in his PHP examples. This is answered below, using the `Process` library. – Keith Feb 20 '17 at 18:09
  • @Keith good answer below :) I just gave him the idea as he asked for other techniques as well – hhafeez Feb 20 '17 at 18:22

1 Answers1

1

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();
    }
} 
Keith
  • 3,079
  • 2
  • 17
  • 26