Getting the output from a sub-process

A few times recently i’ve needed to capture the output from an OS specific command in Java.   It’s not terribly difficult, but this little example may save you some time.

package test;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
    private final static String COMMAND = "/usr/bin/uptime";

    public static void main(String[] args) throws Exception {

       Process process = Runtime.getRuntime().exec(COMMAND);
       BufferedReader stdout =
            new BufferedReader(new InputStreamReader(process.getInputStream()));
       String line = "";
       while ((line=stdout.readLine())!=null) {
          System.out.println(line);
       }
       process.waitFor();  // unlikely we'd ever wait as we've got EOF on stdout
       System.out.println("Exit code = "+process.exitValue());
    }
}

And here is the output as you would expect :

 08:30:47 up 12 days, 23:53,  1 user,  load average: 1.87, 1.99, 2.07
Exit code = 0
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s