ã©ã¤ãã©ãªã使ããã«JavaããRã使ã
çµ±è¨è§£æå¨RãJavaã§ä½¿ãã
RãJavaã§æ±ãã©ã¤ãã©ãªãããããã ãã©ã
ã©ã¤ãã©ãªã®ä¸ãç解ããã®ã大å¤ãããªã®ã§ã
ã©ã¤ãã©ãªã使ããã«Rã®åºåãJavaã§åãåãããã
ã¨ããããã§ããã£ã¦ã¿ãã
ã³ã¼ã
help()ã³ãã³ããå®è¡ããæã®åºåãåãåãã
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; /** * * @author Syu_Syu */ public class Rcmd { public String commander()throws IOException { String result = new String(); ProcessBuilder builder = new ProcessBuilder("/usr/bin/R","-q","--no-save"); Process process = builder.start(); OutputStream os = process.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); bw.write("help()"); bw.flush(); bw.close(); InputStream is = process.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line_tmp = new String(); String line = new String(); while((line_tmp = br.readLine()) != null){ line += line_tmp +"\n"; System.out.println(line_tmp); } br.close(); InputStream stream = process.getErrorStream(); while(true){ int c = stream.read(); if(c == -1){ stream.close(); break; } System.out.print((char)c); } result = line; return result; } }
ã©ã¤ã»ã³ã¹è¡¨ç¤ºã®çç¥
Rãèµ·åããã¨ä»¥ä¸ã®æç« ã表示ãããã
R version 2.10.1 (2009-12-14) Copyright (C) 2009 The R Foundation for Statistical Computing ISBN 3-900051-07-0 Rã¯ãèªç±ãªã½ããã¦ã§ã¢ã§ããããå®å ¨ã«ç¡ä¿è¨¼ãã§ãã ä¸å®ã®æ¡ä»¶ã«å¾ãã°ãèªç±ã«ãããåé å¸ãããã¨ãã§ãã¾ãã é å¸æ¡ä»¶ã®è©³ç´°ã«é¢ãã¦ã¯ã'license()'ãããã¯'licence()'ã¨å ¥åãã¦ãã ããã Rã¯å¤ãã®è²¢ç®è ã«ããå ±åããã¸ã§ã¯ãã§ãã 詳ããã¯'contributors()'ã¨å ¥åãã¦ãã ããã ã¾ããRãRã®ããã±ã¼ã¸ãåºçç©ã§å¼ç¨ããéã®å½¢å¼ã«ã¤ãã¦ã¯ 'citation()'ã¨å ¥åãã¦ãã ããã 'demo()'ã¨å ¥åããã°ãã¢ãã¿ããã¨ãã§ãã¾ãã 'help()'ã¨ããã°ãªã³ã©ã¤ã³ãã«ããåºã¾ãã 'help.start()'ã§HTMLãã©ã¦ã¶ã«ãããã«ããã¿ããã¾ãã 'q()'ã¨å ¥åããã°Rãçµäºãã¾ãã
æ¨æºåºåãStringã§åã£ã¦ãã¦ããã®ã§ããã®æç« ãåã£ã¦ãã¦ãã¾ãã
ããã§ãé表示ã«ãããªãã·ã§ã³ã使ãã
ProcessBuilder builder = new ProcessBuilder("/usr/bin/R","-q","--no-save");
ãã®"-q","--no-save"ããªãã·ã§ã³ã
ã-qã§ã©ã¤ã»ã³ã¹ãé表示ã«ã§ããã
ã--no-saveã§å®è¡ããRãä¿åããªãè¨å®ã«ãã¦ããã
è¤æ°ã®ã³ãã³ãå ¥å
以ä¸ã®ã³ã¼ãã§help()ã³ãã³ããå ¥åãã¦ããã
bw.write("help()");
bw.flush();
bw.close();
ä¾ãã°ãç¶ãã¦getwd()ã³ãã³ããå ¥åãããæã¯ã以ä¸ã®ããã«ããã
bw.write("help()\n"); bw.flush(); bw.write("getwd()"); bw.flush(); bw.close();
ã¾ãã¯ã以ä¸ã®ããã«ã\nã§ç¹ãã¦æ¸ãã¦ãè¯ãã
bw.write("help()\ngetwd()"); bw.flush(); bw.close();
ã¨ã©ã¼å¦çã¯å¿ é
以ä¸ã®ã³ã¼ãã¯ãã¨ã©ã¼å¦çã¨ãã¦çµ¶å¯¾ã«å¿ è¦ã
InputStream stream = process.getErrorStream(); while(true){ int c = stream.read(); if(c == -1){ stream.close(); break; } System.out.print((char)c); }
ãã®ã¨ã©ã¼å¦çããªãã¨ããã¾ãåããªãã
ããã
åã£ã¦ããStringã¯ã以ä¸ã®ããã«ã³ãã³ããåºåããã¦ããã
> getwd() [1] "/home/username/NetBeansProjects/projectname" >
ãã®ãããå¥ã®ããã°ã©ã ã§å¿ è¦ãªé¨åã ãæ½åºãã¦ããå¿ è¦ãããã