0

I got following simple R-program named hello.R:

print('hello')

I like to call this code from Java now. This is my code in Java:

import java.io.IOException;

public class Main {

    public static void main(String[] args) {
        String path = "C:\\Users\\Administrator\\Desktop\\hello.R";
        try {
            Runtime.getRuntime().exec("C:\\Program Files\\R\\R-3.1.3\\bin\\Rscript "+path);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

    }

}

I was expecting it to print the hello statement in the Java concole. But Java program didn't do anything at all.

Do you know what the problem may be?

XerXes
  • 337
  • 1
  • 16

2 Answers2

0

Based on this answer I think you should do the following:

ProcessBuilder pb = new ProcessBuilder("/path/to/Rscript", "/path/to/hello.r");
pb.redirectOutput(Redirect.INHERIT);
pb.redirectError(Redirect.INHERIT);
Process p = pb.start();

This redirects both the output stream and the error stream of the subprocess to the current process, allowing you to observe the contents in the Java console.

rinde
  • 1,181
  • 1
  • 8
  • 20
  • I tried this, but unfortunately I get an error message: java.io.IOException: Cannot run program "C:\Program Files\R\R-3.1.3\bin\Rscript C:\Users\Administrator\Desktop\hello.R": CreateProcess error=2, The system cannot find the file specified at java.lang.ProcessBuilder.start(Unknown Source) at Main.main(Main.java:12) Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified at java.lang.ProcessImpl.create(Native Method) at java.lang.ProcessImpl.(Unknown Source) at java.lang.ProcessImpl.start(Unknown Source) ... 2 more – XerXes Jan 15 '16 at 16:09
  • There was a mistake in my code example (the command and its argument need to be separated), I updated my answer. – rinde Jan 15 '16 at 16:12
  • Are you sure that the paths you used are correct? You can try the command using Windows command line CMD (assuming you run Windows)? – rinde Jan 18 '16 at 10:49
0

You could try the following to get the hello string in Java:

#* @get /hello
hello <- function() {
  print("hello")
}

You can run the following:

library(plumber)
r <- plumb("hello.R")
r$run(port=8080)

If you then call the page

http://localhost:8080/hello

your R code will be executed.

If you want to execute it from Java the solution could be:

   URL url = new URL("http://localhost:8080/hello");
   URLConnection connection = url.openConnection();
   BufferedReader br = new BufferedReader(new InputStreamReader( (connection.getInputStream())));
   String result = br.readLine();
Volokh
  • 380
  • 3
  • 16