FileReader can't find R Script

183 views Asked by At

I try run my R Script within JavaFx. I use Renjin for this purpose and it seems to work properly with statements I run internally. But I want to run an external R Script. The project is set up with Maven so the path should be easy as the R Script is in the resources folder. The path works when I load FXML files, so I'm pretty confused why it can't find my Script.

Here's a short example:

package survey;

import javax.script.*;
import org.renjin.script.*;
import java.io.FileReader;

public class calcFunction {

  public static void main(String[] args) throws Exception {
    // create a script engine manager:
    RenjinScriptEngineFactory factory = new RenjinScriptEngineFactory();
    // create a Renjin engine:
    ScriptEngine engine = factory.getScriptEngine();

    engine.put("x", 4);
    engine.put("y", 5);

    engine.eval(new FileReader("/test.R"));
  }

}

Is something missing? Thanks in advance!

EDIT1:

With my FXML files it works with the "/" path like this:

 root = FXMLLoader.load(getClass().getResource("/moduleDa.fxml"));   

EDIT2:

Someone who deleted his comment proposed this:

engine.eval(new FileReader(new File(".").getAbsolutePath()+"/test.R"));

It works if the script is in the root directory, where the pom.xml file is located. @James_D made it work so the R script can be located in the resources folder - thanks a lot!

1

There are 1 answers

0
James_D On BEST ANSWER

If your R script is bundled as part of the application, it can't be treated as a file - you need to treat it as a resource. Typically, you will deploy your application as a Jar file, and the resources will be elements within that jar file (they won't be files in their own right).

So just treat the R script as a resource and load it as such. I don't know the renjin framework, but I assume ScriptEngine here is a javax.script.ScriptEngine, in which case ScriptEngine.eval(...) takes a Reader as a parameter, and so (if your R script is located in the root of the class path) you can do

engine.eval(new InputStreamReader(getClass().getResourceAsStream("/test.R")));