0

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

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yes it is the getErrorStream. Thank you for your quick answer!
Also note that if you wait for the process to finish before reading, the process may deadlock if it outputs more than the system's pipe buffer size (e.g. 65k on Linux).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.