Dustin Sun
Dustin Sun

Reputation: 5532

Java Runtime.getRuntime().exec unable to catch all output

My shell script run.sh

echo "Running my.r"
Rscript /opt/myproject/my.r

Output of run.sh from command line

Running my.r
2019-06-14 job starts at 2019-06-13 16:52:21
========================================================================
1. Load parameters from csv files.
Error in file(file, "rt") : cannot open the connection
Calls: automation.engine ... %>% -> eval -> eval -> read.csv -> read.table -> file
In addition: Warning message:
In file(file, "rt") :
  cannot open file '/...../_nodes.csv': No such file or directory

However my Java program can only capture the first line "Running my.r". How can I catch every single line of the output? Below is my Java code:

Process proc = Runtime.getRuntime().exec("/opt/myproject/run.sh");
            BufferedReader read = new BufferedReader(new InputStreamReader(
                    proc.getInputStream()));
            try {
                proc.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
                throw e;
            }
            while (read.ready()) {
                String line = new String(read.readLine());
                results += "\r\n" + line;
                System.out.println(line);
            }

Upvotes: 0

Views: 296

Answers (1)

Antoniossss
Antoniossss

Reputation: 32550

That is because you are only capturing standard output from Process#getInputStream (like System.out) and errors are printed in error stream (System.err). You will have to capture Process#getErrorStream() as well.

Instead of Runtime.exec() you can use ProcessBuilder and then invoke redirectErrorStream on it to merge those 2 streams.

https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html#redirectErrorStream()

Upvotes: 3

Related Questions