Sebastian Zeki
Sebastian Zeki

Reputation: 6874

How to run R script from java using Process builder

This should be simple but I keep getting an error. I have a swing application. When the user presses a button they are prompted to choose a R file to open. The Rscript path is stored in a user preference. The Processbuilder should then run the script:

The method for the Processbuilder is as follows

 public static void open(File document) throws IOException, ScriptException {
        Preferences userPrefs = Preferences.userNodeForPackage(TBB_SQLBuilder.class);
        String pt=document.getAbsolutePath().toString().trim()   
        Process process = new ProcessBuilder(userPrefs.get("PathToR",null)+" '"+pt+"'").start();
  }

However it gives me the error:

java.io.IOException: Cannot run program "/Applications/RStudio.app '/Users/sebastianzeki/Myscript.R'": error=2, No such file or directory

When I change the R path (on MacOSX ElCapitaine) to /Library/Frameworks/R.framework/Versions/3.1/Resources/Rscript then I get the same error

Trying to run Runtime.getRuntime().exec(userPrefs.get("PathToR",null)); also gives me an error but this time it is:

Cannot run program "/Applications/RStudio.app": error=13, Permission denied

but I don't get this when I use Rscript The permissions on RStudio and Rscript are set to read and write for everyone.

All I would like to do is run my script in R (this outputs a csv which my application picks up)

I am aware of Renjin (no dplyr support) JRI and rJava (messy installation with paths etc) and RServe (just don't like it) so Process builder running my script as an external script is the best option for me.

What am I doing wrong?

Upvotes: 0

Views: 540

Answers (1)

kgeorgiy
kgeorgiy

Reputation: 1477

The constructor of ProcessBuilder takes not the command line, but the command and its arguments. So, in this example it should be constructed as

new ProcessBuilder(userPrefs.get("PathToR",null), pt);

This builder will run R with single argument pt. Notice, that even if pt contains spaces, it will be interpreted as a single argument.

Upvotes: 1

Related Questions