In Java, I want to run a script in the separate terminal window, on the Mac Os X:
Runtime.getRuntime().exec("/usr/bin/open -a Terminal script.sh")
How can I get the output of this script?
In Java, I want to run a script in the separate terminal window, on the Mac Os X:
Runtime.getRuntime().exec("/usr/bin/open -a Terminal script.sh")
How can I get the output of this script?
Use the following way to read the outout of the command, the result
string will have the output
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();
Using a BufferedReader
seems to be an easy approach.
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()