如何从 Java 自动启动 Rserve?

How to start Rserve automatically from Java?

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

R
library(Rserve)
Rserve()

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

我知道这个问题已经被问了很久了。我想你有答案。但是下面的答案可能会对其他人有所帮助。这就是我发布答案的原因。 回答:- 而不是一次又一次地去 R 控制台启动 Rserve。您可以做的一件事是编写 java 程序来启动 Rserve。

您可以在 java 程序中使用下面的代码来启动 Rserve。 https://www.sitepoint.com/community/t/call-linux-command-from-java-application/3751。这是 link,您将在其中获取代码 运行 来自 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();
        }
              }
           }

这是我为 RserveJava

开始工作而编写的 Class 代码
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);
        }
    }
}