package examples;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

//import java.util.ArrayList;

public class ExecDemo {
    static public String[] runCommand(String cmd)
            throws IOException {

        // set up list to capture command output lines

        ArrayList list = new ArrayList();

        // start command running

        Process proc = Runtime.getRuntime().exec(cmd);

        // get command's output stream and
        // put a buffered reader input stream on it

        InputStream istr = proc.getInputStream();
        BufferedReader br =
                new BufferedReader(new InputStreamReader(istr));

        // read output lines from command

        String str;
        while ((str = br.readLine()) != null)
            list.add(str);

        // wait for command to terminate

        try {
            proc.waitFor();
        } catch (InterruptedException e) {
            System.err.println("process was interrupted");
        }

        // check its exit value

        if (proc.exitValue() != 0)
            System.err.println("exit value was non-zero");

        // close stream

        br.close();

        // return list of strings to caller

        return (String[]) list.toArray(new String[0]);
    }

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

            // run a command

            String outlist[] = runCommand("test");

            // display its output

            for (int i = 0; i < outlist.length; i++)
                System.out.println(outlist[i]);
        } catch (IOException e) {
            System.err.println(e);
        }
    }
}