您可以等待Process
(exec
返回一个Process
对象) 完成waitFor
,然后检查退出值:它应该是 0。
如果它不为零,您可能需要指定脚本的路径。
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");
}
如果退出值不为 0,您可以按照 Andrew 的评论中的建议查看进程的 stdout 和 stderr。
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");
}
正如评论中提到的,您需要明确打开设备。由于脚本终止时它是关闭的,因此您还需要添加延迟。
x11() # Open a device (also works on Windows)
plot( rnorm(10) )
Sys.sleep(10) # Wait 10 seconds