我正在尝试从Java启动R进程并重定向stdin和stdout。
processBuilder = new ProcessBuilder().command("/usr/bin/R").redirectErrorStream(
true);
try {
Process p = processBuilder.start();
OutputStream stdin = p.getOutputStream();
InputStream stdout = p.getInputStream();
BufferedReader reader = new BufferedReader (new InputStreamReader(stdout));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
String line;
while ((line = reader.readLine ()) != null) {
System.out.println ("Stdout: " + line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我正在使用Java 1.6。程序运行时,我收到以下错误:
标准输出:致命错误:您必须指定'--save',' - no-save'或'--vanilla'
任何帮助将不胜感激!谢谢!
答案 0 :(得分:2)
您不能只使用重定向的stdin运行R而没有其中一个选项:
R < foo.R
Fatal error: you must specify '--save', '--no-save' or '--vanilla'
你想让R在完成时保存其工作数据(--save)吗?或不( - 没有 - 保存)?您可能会发现--vanilla适合您的使用。
--vanilla
Combine --no-save, --no-restore, --no-site-file, --no-init-file and --no-environ
我不太清楚如何将参数传递给Java ProcessBuilder的东西,但也许只是:
processBuilder = new ProcessBuilder().command("/usr/bin/R --vanilla").redirectErrorStream(
true);
或者它可能有设置args的方法。
答案 1 :(得分:1)
以下是在将参数作为子进程启动时将参数传递给R的方法:
public void startR() {
List<String> commandAndParams = new ArrayList<String>();
commandAndParams.add("/usr/bin/R");
commandAndParams.add("--vanilla");
processBuilder = new ProcessBuilder().command(commandAndParams).redirectErrorStream(
true);
try {
Process p = processBuilder.start();
OutputStream stdin = p.getOutputStream();
InputStream stdout = p.getInputStream();
BufferedReader reader = new BufferedReader (new InputStreamReader(stdout));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
String line;
while ((line = reader.readLine ()) != null) {
System.out.println ("Stdout: " + line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
结果输出为:
Stdout:
Stdout: R version 3.0.1 (2013-05-16) -- "Good Sport"
Stdout: Copyright (C) 2013 The R Foundation for Statistical Computing
Stdout: Platform: x86_64-apple-darwin10.8.0 (64-bit)
Stdout:
Stdout: R is free software and comes with ABSOLUTELY NO WARRANTY.
Stdout: You are welcome to redistribute it under certain conditions.
Stdout: Type 'license()' or 'licence()' for distribution details.
Stdout:
Stdout: Natural language support but running in an English locale
Stdout:
Stdout: R is a collaborative project with many contributors.
Stdout: Type 'contributors()' for more information and
Stdout: 'citation()' on how to cite R or R packages in publications.
Stdout:
Stdout: Type 'demo()' for some demos, 'help()' for on-line help, or
Stdout: 'help.start()' for an HTML browser interface to help.
Stdout: Type 'q()' to quit R.
Stdout: