Surras Surras - 1 year ago 86
Java Question

Read live output of process in java

I start a python script in my java application with

Process p = Runtime.getRuntime().exec("python");

This script runs in a loop and is only canceled by an event (or user interaction). The script writes to the output every loop cycle, some text like "12:22:35 -- Heartbeat"

while True:

In my Java application I want to read this output as it appears. My problem is, if I use the BufferReader, it will wait until the process is completed and after that it reads the output. Here is how I read it:

BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;

while ((line = is.readLine()) != null)

How can I read the output "live"?

For better understanding: the python-script listen on a hardware button, and when this button is pressed, some output is written out. And in my java application I want to show up this message and sent it to some clients.

Answer Source


new ProcessExecutor().command("python", "")
    .redirectOutput(new LogOutputStream() {
        protected void processLine(String line) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download