Home > Back-end >  How to print the live data from ProcessBuilder to console in Java?
How to print the live data from ProcessBuilder to console in Java?

Time:10-20

Below is my code to read the output from console. I need to read the tracert path live to console.

Below code prints the data at once after finishing the process only.

Can someone help me?

ProcessBuilder f = new ProcessBuilder("cmd.exe","tracert ip_address");
Process p = f.start();

BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader readers = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String lines =null;
System.out.println();

while((lines = reader.readLine())!=null) {
    System.out.println("lines:" lines);
}

String lines1 =null;
while((lines1 = readers.readLine())!=null) {
    System.out.println("error lines:" lines1);
}

CodePudding user response:

Here are some suggestions which should help.

You do not need to use CMD.EXE to launch TRACERT.EXE, as you can run it directly if it is on the path or fully qualify it's path. If you do use CMD then use "/C" flag to ensure it runs just that command.

String ip = "bbc.com";
String [] cmd = {"cmd.exe", "/c", "tracert " ip};
System.out.println("Running:" Arrays.toString(cmd));

Consuming STDOUT and STDERR in same thread can lead to the process freezing if it writes large amounts. Use files redirects, or redirect ERR->OUT:

ProcessBuilder f = new ProcessBuilder(cmd);
f.redirectErrorStream(true);
Process p = f.start();

Don't waste time with a loop over the output, send to a new ByteArrayOutputStream() if you want to capture it, or just to System.out:

try(var stdout = p.getInputStream()) {
   stdout.transferTo(System.out);
}

Always wait for the process to end:

int rc = p.waitFor();

System.out.println("Exit:" p.pid() " RESULT:" rc  ' ' (rc == 0 ? "OK":"**** ERROR ****"));
  • Related