Collect Linux command output

Viewed 22357

I am now on a linux machine. I have a Java program which would run some linux command, for example ps, top, list or free -m.

The way to run a command in Java is as follows:

Process p = Runtime.getRuntime().exec("free -m");

How could I collect the output by Java program? I need to process the data in the output.

5 Answers
public String RunLinuxGrepCommand(String command) {
    String line = null;
    String strstatus = "";
    try {

        String[] cmd = { "/bin/sh", "-c", command };
        Process p = Runtime.getRuntime().exec(cmd);
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((line = in.readLine()) != null) {
            strstatus = line;
        }
        in.close();
    } catch (Exception e) {

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        pw.flush();
        String stackTrace = sw.toString();
        int lenoferrorstr = stackTrace.length();
        if (lenoferrorstr > 500) {
            strstatus = "Error:" + stackTrace.substring(0, 500);
        } else {
            strstatus = "Error:" + stackTrace.substring(0, lenoferrorstr - 1);

        }
    }
    return strstatus;

}

This functioin will give result of any linux command

Related