aggregate1166877
aggregate1166877

Reputation: 3150

Print Runtime.getRuntime().exec() output live

I'm writing a Java program that is used to call a PHP script in set intervals. The PHP script outputs a lot of data, and it is the client's requirement that the Java program displays all the PHP script's output while the script runs.

The method I'm using is:

Runtime.getRuntime().exec(new String[]{"php", "file.php"});

Then using an InputStreamReader to grab output, primarily using examples from here. The problem I'm having is that the stream reader only outputs the data once the PHP script exits (which makes sense considering how the output is looped through).

How would I go about printing the script's output live while the script is running?

Upvotes: 0

Views: 5004

Answers (2)

aggregate1166877
aggregate1166877

Reputation: 3150

For now I decided to go with Andrew Thompson's suggestion:

ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process process = builder.start();

InputStreamReader istream = new  InputStreamReader(process.getInputStream());
BufferedReader br = new BufferedReader(istream);

String line;
while ((line = br.readLine()) != null){
   System.out.println(line);
}

process.waitFor();

This is still not what I'm looking for though, so for now I'm leaving the question unanswered.

Upvotes: 0

Dan D.
Dan D.

Reputation: 32391

I did this by reading the output from a separate thread:

  Process p = Runtime.getRuntime().exec(commands);
  final InputStream stream = p.getInputStream();
  new Thread(new Runnable() {
    public void run() {
      BufferedReader reader = null;
      try {
        reader = new BufferedReader(new InputStreamReader(stream));
        String line = null;
        while ((line = reader.readLine()) != null) {
          System.out.println(line);
        }
      } catch (Exception e) {
        // TODO
      } finally {
        if (reader != null) {
          try {
            reader.close();
          } catch (IOException e) {
            // ignore
          }
        }
      }
    }
  }).start();

Upvotes: 5

Related Questions