本文介绍了如何从Java自动启动Rserve?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a Java application in IntelliJ IDE. The application used Rserve package to connect to R and perform some functions. When I want to run my code for the first time, I have to launch R in the command line and start the Rserve as a daemon, which looks something like this:

R
library(Rserve)
Rserve()

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

After doing this, I can easily access all the function in R without any errors. However, since this Java code would be bundled as an executable file, so is there a way that Rserve() is invoked automatically as soon as the code is run so that I have to skip this manual step of starting Rserve using the command line?

推荐答案

以下是我写的 Class 的代码code> Rserve 工作于 Java

Here is the code for the Class I wrote to get Rserve working from 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自动启动Rserve?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 18:54