我正在用Java编写一个IntelliJ应用程序。该应用程序使用Rserve包连接到R并执行一些功能。当我想第一次运行我的代码时,我必须在命令行中启动R并以守护进程的形式启动Rserve,如下所示:
R
library(Rserve)
Rserve()这样做之后,我可以轻松地访问R中的所有函数,而不会有任何错误。但是,由于这个Java代码将被捆绑为一个可执行文件,那么是否有一种方法可以在代码运行后立即自动调用Rserve(),因此我必须跳过使用命令行启动Rserve的手动步骤吗?
发布于 2016-04-19 12:12:53
下面是我为使Class从Java中运行而编写的Rserve的代码
public class InvokeRserve {
public static void invoke() {
String s;
try {
// run the Unix ""R CMD RServe --vanilla"" command
// using the Runtime exec method:
Process p = Runtime.getRuntime().exec("R CMD RServe --vanilla");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
// System.exit(0);
}
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
}发布于 2015-11-24 11:52:28
我知道这个问题已经问了很久了。我想你有答案了。但下面的答案可能会对其他人有所帮助。这就是为什么我要贴出我的答案。回答:-而不是一次又一次地去R控制台启动Rserve。您可以做的一件事是可以编写一个java程序来启动Rserve。
下面的代码可以在java程序中使用来启动Rserve。https://www.sitepoint.com/community/t/call-linux-command-from-java-application/3751。这是一个链接,您将从java.I只更改该命令并在下面发布运行linux命令的代码。
package javaapplication13;
import java.io.*;
public class linux_java {
public static void main(String[] args) {
try {
String command ="R CMD Rserve";
BufferedWriter out = new BufferedWriter(new FileWriter(
new File(
"/home/jayshree/Desktop/testqavhourly.tab"), true));
final Process process = Runtime.getRuntime().exec(command);
BufferedReader buf = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line;
while ((line = buf.readLine()) != null) {
out.write(line);
out.newLine();
}
buf.close();
out.close();
int returnCode = process.waitFor();
System.out.println("Return code = " + returnCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}https://stackoverflow.com/questions/32373372
复制相似问题