在Java中,我想在Mac OS X的单独的终端窗口中运行脚本:
Runtime.getRuntime().exec("/usr/bin/open -a Terminal script.sh")
如何获取此脚本的输出?
答案 0 :(得分:1)
使用以下方式读取命令的内容,result
字符串将输出
Process process = Runtime.getRuntime().exec(command);
InputStream inputStream = process.getInputStream();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder output = new StringBuilder();
String line = null;
while((line = stdInput.readLine()) != null) {
output.append(line);
}
inputStream.close();
process.waitFor();
String result = output.toString();
答案 1 :(得分:0)
使用BufferedReader
似乎是一种简单的方法。
import java.io.*;
import java.util.stream.*;
. . .
Process p = Runtime.getRuntime().exec("/usr/bin/open -a Terminal script.sh");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
// perhaps retrieve all the lines as a stream for future processing
// i.e. map, filter, reduce, etc.
Stream<String> lines = input.lines();
// or go line by line from the BufferedReader
String line;
while ((line = input.readLine()) != null) {
// do something with line
}
// To just retrieve all the output as a single String
String output = input.lines().collect(Collectors.joining("\n"));
. . .
input.close()