Java - Execute system command and redirect the output

Subscribe Send me a message home page tags

In this post, we will see how we can execute a system command in Java and redirect its output and error message.

In order to execute a system command in Java, we need to create a Process object. There are different ways doing that and one option is to create a ProcessBuilder. For instance, the example below shows how we can execute the diff command.
ProcessBuilder builder = new ProcessBuilder("diff", "-u", FIRST_FILE, SECOND_FILE);

Process p = builder.start();

Both of Process class and Process class provide methods to redirect outputs and error message of the underlying process that they represent. In our case, we will use the getInputStream() and getErrorSream() mtehods from the Process class. Note that the getInputStream() is the output stream of the subprocess. It is called input stream because from the point of the client of the Process object, the output of the subprocess is its input.
BufferedReader readerOfOutput = new BufferedReader(new InputStreamReader(p.getInputStream()));

String line;
while ((line = readerOfOutput.readLine()) != null) {

BufferedReader readerOfError = new BufferedReader((new InputStreamReader(p.getErrorStream())));

while ((line = readerOfError.readLine()) != null) {

----- END -----