2016-08-16 282 views
0

我試圖從我的Java代碼執行R腳本。 這是java代碼我有Rserve:拒絕連接:連接

package pkg; 

import org.rosuda.REngine.REXPMismatchException; 
import org.rosuda.REngine.Rserve.RConnection; 
import org.rosuda.REngine.Rserve.RserveException; 

public class Temp { 
public static void main(String a[]) { 
    RConnection connection = null; 

    try { 
     /* Create a connection to Rserve instance running on default port 
     * 6311 
     */ 
     connection = new RConnection(); 

     connection.eval("source('D:\\\\r script\\\\TestRserve.R')"); 
     connection.eval("Rserve()"); 
     int num1=10; 
     int num2=20; 
     int sum=connection.eval("myAdd("+num1+","+num2+")").asInteger(); 
     System.out.println("The sum is=" + sum); 
    } catch (RserveException e) { 
     e.printStackTrace(); 
    } catch (REXPMismatchException e) { 
     e.printStackTrace(); 
    } 
} 
} 

的TestRserve.R是如下

library(Rserve) 
    Rserve() 
    x= matrix(c(1,2,3,4,5,6)) 
    plot.ts(x) 

我已經從一個教程中使用的示例代碼和AFAIK,沒有在Java正在執行的TestRserve文件。我也曾嘗試類似下面執行TestRserve.R

 REXP x; 
     System.out.println("Reading script..."); 
     File file = new File("D:\\r script\\TestRserve.R"); 
     try(BufferedReader br = new BufferedReader(new FileReader(file))) { 
      for(String line; (line = br.readLine()) != null;) { 
       System.out.println(line); 
       x = c.eval(line);   // evaluates line in R 
       System.out.println(x); // prints result 
      } 
     } 

以下是堆棧跟蹤

異常線程「main」 org.rosuda.REngine.Rserve.RserveException:無法連接:連接被拒絕:在org.rosuda.REngine.Rserve.RConnection。(RConnection.java:88) 處連接 at org.rosuda.REngine.Rserve.RConnection。(RConnection.java:60) at org.rosuda.REngine .Rserve.RConnection。(RConnection.java:44) at functionTest.HelloWorldApp.main(HelloWorldApp.java:17)

回答

1

關於Rserve的一些誤解可從您的代碼中辨別出來。

首先,Rserve是一個服務器,Rserve JAR文件提供了與Rserve交互的客戶端實現,就像npm上有JavaScript客戶端一樣。

因此,要通過Rserve調用R腳本,Rserve服務器需要已經啓動並等待接收呼叫。這可以來自R使用來完成:

Process p = Runtime.getRuntime().exec("R CMD RServe --vanilla"); 

雖然這也:

library(Rserve) 
Rserve() 

或從Linux的bash 或使用JavaRuntime API訪問運行時直接從Java調用它,: R CMD Rserve --vanilla直接僅適用於Linux。

然後,您應該執行Java客戶端代碼,通過Rserve連接到Rserve服務器和所有R命令。