Home:ALL Converter>Run R script in java code and output r result into text file

Run R script in java code and output r result into text file

Ask Time:2013-01-11T00:30:52         Author:Caroline Kou

Json Formatter

I am trying to run R script in java program and output the result into text file.

Here is my java code:

import java.io.*;

public class rclass {

    public static void main(String[] args) {
        try {

            String line;

            Process p = Runtime.getRuntime().exec("RScript /Users/test.R iphone5 2012-12-16 2013-01-03");
            p.waitFor();

            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

            while((line = input.readLine()) != null) {

                System.out.println(line);

            }

            input.close();

        } catch(Exception e) {
          e.printStackTrace();
        }
    }
}

Here's how I output r result into text file:

out<-capture.output(scores)
cat(out, file="/Users/mmmmmm/Desktop/result.txt", sep="\n",append=TRUE)

When I run the java code, there's no output from my r script into text file. But when I run the command from terminal, it works well. I cannot to find the problem. Could anyone please give me some suggestions?

Author:Caroline Kou,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/14262655/run-r-script-in-java-code-and-output-r-result-into-text-file
yy