我試圖從我的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)