您将必须
/usr/bin/Rscript直接运行。另外,该程序不会从标准输入中读取脚本(您必须将脚本的路径指定为的参数
Rscript),因此您必须:
- 创建一个临时文件
- 写你的脚本
- 用Rscript执行脚本
- 删除您的临时文件(作为良好的编程习惯)
例如,这是一个POC:
public static void main(String[] args) throws IOException, InterruptedException { // Your script String script = "#!/usr/bin/env Rscriptn" + "n" + "sayHello <- function() {n" + " print('hello')n" + "}n" + "n" + "sayHello()n"; // create a temp file and write your script to it File tempscript = File.createTempFile("test_r_scripts_", ""); try(OutputStream output = new FileOutputStream(tempscript)) { output.write(script.getBytes()); } // build the process object and start it List<String> commandList = new ArrayList<>(); commandList.add("/usr/bin/Rscript"); commandList.add(tempscript.getAbsolutePath()); ProcessBuilder builder = new ProcessBuilder(commandList); builder.redirectErrorStream(true); Process shell = builder.start(); // read the output and show it try(BufferedReader reader = new BufferedReader( new InputStreamReader(shell.getInputStream()))) { String line; while((line = reader.readLine()) != null) { System.out.println(line); } } // wait for the process to finish int exitCode = shell.waitFor(); // delete your temp file tempscript.delete(); // check the exit pre (exit pre = 0 usually means "executed ok") System.out.println("EXIT CODE: " + exitCode);}或者, 如果您的脚本的第一行带有“ shebang”,则 可以进行以下更改:
- 将其可执行属性设置为“ true”
- 使用临时文件的路径作为commandList中的第一个元素(即delete
commandList.add("/usr/bin/Rscript");)
要修改的代码部分为:
...// create a temp file and write your script to itFile tempscript = File.createTempFile("test_r_scripts_", "");tempscript.setExecutable(true);try(OutputStream output = new FileOutputStream(tempscript)) { output.write(script.getBytes());}// build the process object and start itList<String> commandList = new ArrayList<>();commandList.add(tempscript.getAbsolutePath());ProcessBuilder builder = new ProcessBuilder(commandList);...


