You can wait for the Process
(exec
returns a Process
object) to finish
with waitFor
, and check the exit value: it should be 0.
If it is not zero, you probably need to specify the path of the script.
public static void main( String[] args ) throws IOException, InterruptedException {
Process p = Runtime.getRuntime().exec("Rscript /tmp/test.R");
System.out.println("Started");
p.waitFor();
if( p.exitValue() != 0 )
System.out.println("Something went wrong");
else
System.out.println("Finished");
}
If the exit value is not 0, you can look at the stdout and stderr of the process,
as suggested in Andrew's comment.
public static void main(String[] args) throws IOException, InterruptedException {
System.out.println("test...");
Process p = Runtime.getRuntime().exec(new String[] {
"Rscript",
"-e",
"print(rnorm(5)))" // Intentional error, to produce an error message
} );
System.out.println("Started");
String line = null;
System.out.println("Stdout:");
BufferedReader stdout = new BufferedReader( new InputStreamReader( p.getInputStream() ) );
while ( (line = stdout.readLine()) != null)
System.out.println(line);
System.out.println("Stderr:");
BufferedReader stderr = new BufferedReader( new InputStreamReader( p.getErrorStream() ) );
while ( (line = stderr.readLine()) != null)
System.out.println(line);
p.waitFor();
if( p.exitValue() != 0 )
System.out.println("Something went wrong, exit value=" + p.exitValue());
else
System.out.println("Finished");
}
As mentionned in the comments,
you need to explicitly open the device.
Since it is closed when the script terminates, you also need to add a delay.
x11() # Open a device (also works on Windows)
plot( rnorm(10) )
Sys.sleep(10) # Wait 10 seconds