0

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?

2 Answers2

1

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();
Lakshya Garg
  • 736
  • 2
  • 8
  • 23
0

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()
Derek Plautz
  • 108
  • 1
  • 5
  • Thank you, but in the buffer reader, you will have an output of another process. ```open -a Terminal``` will open a new terminal window and I don't know how to handle it's output – Nikita Chegodaev Apr 23 '19 at 18:13