JRI:如何在Java String中获取控制台输出

时间:2015-02-26 13:30:38

标签: rjava jri

我在Java程序中声明JRI引擎如下:

REngine eng = REngine.engineForClass("org.rosuda.REngine.JRI.JRIEngine", 
    args, new REngineStdOutput(), false);

这很好但是我想在Java String而不是Java控制台中获得控制台输出。

我研究过REngineStdOutput,但找不到多少。有任何想法吗?

2 个答案:

答案 0 :(得分:0)

您必须实现org.rosuda.JRI.RMainLoopCallbacks接口 - 特别是rWriteConsole()将使用每个输出字符串调用。

答案 1 :(得分:0)

Bellow是如何将R输出显示为Java的示例。你基本上必须实现RMainLoopCallbacks

import org.rosuda.JRI.RMainLoopCallbacks;
import org.rosuda.JRI.Rengine;
import java.util.logging.Logger;

public class Runner {

    private static Logger log = Logger.getLogger("Runner");

    static class LoggingConsole implements RMainLoopCallbacks {
        private Logger log;

        LoggingConsole(Logger log) {
            this.log = log;
        }

        public void rWriteConsole(Rengine re, String text, int oType) {
            log.info(String.format("rWriteConsole: %s", text));
        }

        public void rBusy(Rengine re, int which) {
            log.info(String.format("rBusy: %s", which));
        }

        public void rShowMessage(Rengine re, String message) {
            log.info(String.format("rShowMessage: %s",  message));
        }

        public String rReadConsole(Rengine re, String prompt, int addToHistory) {
            return null;
        }

        public String rChooseFile(Rengine re, int newFile) {
            return null;
        }

        public void rFlushConsole(Rengine re) {
        }

        public void rLoadHistory(Rengine re, String filename) {
        }

        public void rSaveHistory(Rengine re, String filename) {
        }
    }

    Rengine engine = new Rengine(new String[] {"--no-save"}, false, new LoggingConsole(log));
    ...
    // Use the engine somewhere to evaluate a R method and see the output
    engine.eval("library(caret)");
}