Julio Diaz
Julio Diaz

Reputation: 9437

Running command line program inside java program

Im trying to run a program that takes a long time to finish inside a java program. The program inside the java program outputs a huge file (somewhere between 4 to 6 GB). I use the following code inside the main method.

//get the runtime goinog
Runtime rt = Runtime.getRuntime();
//execute program
Process pr = rt.exec("theProgram.exe");
//wqit forprogram to finish
pr.waitFor();

I get a number of errors:

More information:

Upvotes: 0

Views: 202

Answers (2)

Garrett Hall
Garrett Hall

Reputation: 30022

Calling this method with your Process pr will terminate the process when your java program exits:

private void attachShutdownHook(final Process process) {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            process.destroy();
        }
    });
}

If your process has output you can use to assess its progress, then redirect output to java by calling:

private void redirectOutputStreamsToConsole(Process process) {
    redirectStream(process.getInputStream(), System.out);
    redirectStream(process.getErrorStream(), System.err);
}

private void redirectStream(final InputStream in, final PrintStream out) {
    new Thread() {
        @Override
        public void run() {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line = null;
                while ((line = reader.readLine()) != null)
                    out.println(line);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }.start();
}

Upvotes: 1

Austin Heerwagen
Austin Heerwagen

Reputation: 663

It would be a good idea to include pr.destroy() at the end of your Java code so that it terminates the process when your program has ended. This solves error #1

What does pr.exitValue() return in these cases?

Upvotes: 1

Related Questions