How do I automatically start rserve from Java?
•
Java
I write Java applications in the IntelliJ ide The application uses the rserve package to connect to R and perform some functions When I want to run my code for the first time, I must start r on the command line and start rserve as the daemon. It looks like this:
R library(Rserve) Rserve()
After doing this, I can easily access all functions in R without any errors However, since this java code will be bundled into an executable file, there is a way to automatically call rserve () after the code runs, so I have to skip the manual step of starting rserve using the command line?
Solution
This is the code of the class I wrote to make rserve work 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
Sy@R_404_2354@.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
Sy@R_404_2354@.out.println(s);
}
// read any errors from the attempted command
Sy@R_404_2354@.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
Sy@R_404_2354@.out.println(s);
}
// Sy@R_404_2354@.exit(0);
}
catch (IOException e) {
Sy@R_404_2354@.out.println("exception happened - here's what I kNow: ");
e.printStackTrace();
Sy@R_404_2354@.exit(-1);
}
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
