0
votes

I've got a problem when I try to run a R script from Java . I truly look for an answer of this problem on internet but nothing works.

I've used Rserve and Runtime.getRuntime().exec("Rscript myScript.R") but neither of them works with my program.

please help me

this is java code

RConnection c = new RConnection();
                double d[] = c.eval("rnorm(10)").asDoubles();
                org.rosuda.REngine.REXP x0 = c.eval("R.version.string");
                System.out.println(x0.asString());
                Runtime.getRuntime().exec("Rscript TestR.R");

Here is the error message that is being thrown when I add Runtime.getRuntime().exec("Rscript "+rScriptFileName); to the code above:

Exception in thread "main" java.io.IOException: Cannot run program "Rscript": CreateProcess error=2, Le fichier spécifié est introuvable at java.lang.ProcessBuilder.start(Unknown Source) at java.lang.Runtime.exec(Unknown Source) at java.lang.Runtime.exec(Unknown Source) at java.lang.Runtime.exec(Unknown Source) at algo.Testtest.main(Testtest.java:23) Caused by: java.io.IOException: CreateProcess error=2, Le fichier spécifié est introuvable at java.lang.ProcessImpl.create(Native Method) at java.lang.ProcessImpl.(Unknown Source) at java.lang.ProcessImpl.start(Unknown Source) ... 5 more

1
You may need an absolute path to the executable. The file not found exception implies the executable was not found. IIRC, exec(...) will not search your path.KevinO

1 Answers

0
votes

What worked for me was to use the Renjin interpreter Download Renjin

private static final ThreadLocal<ScriptEngine> ENGINE = new ThreadLocal<>();

public static void main(String[] args) {
    ScriptEngine engine = getScriptEngine();
    try {
        System.out.println("myScript");
        engine.eval(new java.io.FileReader("src/myScript.R"));
        engine.eval("Square(19)");
    } catch (FileNotFoundException | NullPointerException | ScriptException e) {
        System.out.println("An exception occured: " + e.getMessage());
        e.printStackTrace();
    }
}

private static ScriptEngine getScriptEngine() {
    ScriptEngine engine = ENGINE.get();
    if (engine == null) {
        // Create a new ScriptEngine for this thread if one does not exist.
        RenjinScriptEngineFactory factory = new RenjinScriptEngineFactory();
        engine = factory.getScriptEngine();
        ENGINE.set(engine);
    }
    return engine;
}