Skip to content

Instantly share code, notes, and snippets.

@pedrominicz
Last active March 15, 2020 01:24
Show Gist options
  • Save pedrominicz/fc8e61d4889942d1c829a6bff7094938 to your computer and use it in GitHub Desktop.
Save pedrominicz/fc8e61d4889942d1c829a6bff7094938 to your computer and use it in GitHub Desktop.
Starting a process with Java.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
public class Exec {
// Java makes it straightforward to create an OS process in any given OS.
// The `ProcessBuilder` class handles everything: which command to
// execute, what environment the process will run in, the working
// directory, the source of the standard input and the destination of the
// standard output, etc.
//
// As the name may imply, one `ProcessBuilder` instance may be called
// multiple times.
public static void main(String[] args) throws IOException {
// Create a process.
final ProcessBuilder processBuilder = new ProcessBuilder("echo", "hello", "world");
final Process process = processBuilder.start();
// Get the output stream of the process. Some Java craziness is
// required to turn the input stream of the process into a string.
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
System.out.println(bufferedReader.lines().collect(Collectors.joining(System.lineSeparator())));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment