简体   繁体   中英

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:

  • when the java program ends theProgram.exe does not stop sometimes the
  • java program never ends even when theProgram.exe has ended
  • theProgram.exe stops without finishing, and the java program does not stop.

More information:

  • I'm using cygwin in Windows7

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?

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM