Java : Running external program

This page last changed on Feb 09, 2006 by Kees de Kooter

Thanks: http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

class StreamGobbler extends Thread {

    InputStream is;
    String type;

    StreamGobbler(InputStream is, String type) {

        this.is = is;
        this.type = type;
    }

    public void run() {

        try {
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null)
                System.out.println(type + ">" + line);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

public class GoodWindowsExec {

    public static void main(String args[]) {

        try {
            String[] cmd = new String[3];

            cmd[0] = "cmd.exe";
            cmd[1] = "/C";
            cmd[2] = args[0];

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

            // any error message?
            StreamGobbler errorGobbler = new StreamGobbler(proc
                    .getErrorStream(), "ERROR");

            // any output?
            StreamGobbler outputGobbler = new StreamGobbler(proc
                    .getInputStream(), "OUTPUT");

            // kick them off
            errorGobbler.start();
            outputGobbler.start();

            // any error???
            int exitVal = proc.waitFor();
            System.out.println("ExitValue: " + exitVal);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

Potential problems

java.io.IOException: CreateProcess: dir error=2

Means: file not found.