How to start Rserve automatically from Java?

二次信任 提交于 2019-12-03 04:58:21

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

I know this question has been asked a long back . I think You have the answer. But the below answer may help others. That's why I am posting my answer. answer:- Instead of going again and again to the R console to start Rserve. One thing you can do is you can write a java program to start Rserve.

Below code you can use in a java program to start Rserve. https://www.sitepoint.com/community/t/call-linux-command-from-java-application/3751. This is the link where you will get the code to run a linux command from java.I have changed the command only and posting below.

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();
        }
              }
           }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!