gpt4 book ai didi

java - 如何从 Java 自动启动 Rserve?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:24:07 28 4
gpt4 key购买 nike

我正在 IntelliJ IDE 中编写 Java 应用程序。该应用程序使用 Rserve 包连接到 R 并执行一些功能。当我想第一次运行我的代码时,我必须在命令行中启动 R 并将 Rserve 作为守护进程启动,它看起来像这样:

R
library(Rserve)
Rserve()

完成此操作后,我可以轻松访问 R 中的所有函数而不会出现任何错误。但是,由于此 Java 代码将被捆绑为一个可执行文件,所以有没有一种方法可以在代码运行时自动调用 Rserve(),这样我就必须跳过使用命令行启动 Rserve 的手动步骤?

最佳答案

这是我为 Rserve 编写的 Class 代码,它可以在 Java 中运行

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

关于java - 如何从 Java 自动启动 Rserve?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32373372/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com