Java调用R

来源:互联网 发布:大数据 消费者洞察 编辑:程序博客网 时间:2024/06/11 04:48
java部分:

import java.io.*;
//import java.util.LinkedList;


public class test 
{
//static private LinkedList<String[]> S_data_table; 
/**
* @param args
* @throws IOException 
* @throws InterruptedException 
*/
public static void main(String[] args) throws IOException, InterruptedException 
{
//---------------------------准备数据S_data_table-------------------
String[] head={"sad", "asd"};
String[] line1={"123", "233"};
String[] line2={"34", "342"};



//---------------------------执行R程序------------------------
String command="C:\\Program Files\\R\\R-3.1.0\\bin\\x64\\Rscript test.R";
Runtime r=Runtime.getRuntime(); 
Process p=null;

p=r.exec(command);


//---------------------------java输出到R程序-------------------------------
OutputStream pOutputStream = p.getOutputStream();
PrintStream output = new PrintStream(pOutputStream, true);



output.println(head[0]+","+head[1]);
output.println(line1[0]+","+line1[1]);
output.println(line2[0]+","+line2[1]);



output.flush();
//-------------------------------------------------------



//-----------------------------R程序输入到java----------------------
InputStreamReader q=new InputStreamReader(p.getInputStream());

BufferedReader br=new BufferedReader(q);
//------------------------读取br的内容-----------------------------------
String msg=null;
while(1==1)
{
msg=br.readLine();

if (msg==null)
{
break;
}
System.out.println(msg);
}

br.close();
q.close();
}


}


R部分:

x<-read.table(file="stdin", head=T, nrows=2)
write.table(x, file=stdout(), quote=F)


运行结果:

sad.asd
1 123,233
2 34,342

0 0
原创粉丝点击