I have command that takes about 4 minutes to complete execution. While executing the command from windows command prompt, it shows timing information and continuous output.
I want to show that output while running the command from my Java code. Normal execution waits until the command exit and get the output. I want to get the output while running without waiting the command to finish.
Here is my code:
try{
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(args);
String line="";
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
errorReader.lines().forEach(System.out::println);
process.waitFor();
System.out.println("---------------------------------------");
}
catch (Exception x){
System.out.println(x.getMessage());
}
Problem with this code is that it wits until the command ends then print all output at once.
The easiest solution is to stop using Runtime.exec, and use the more modern ProcessBuilder class instead. Its inheritIO() method will do exactly what you want:
You can’t read all of a process’s standard output or standard error at once. They can appear concurrently, and failing to read either one might or might not cause a process to hang.
inheritIO()
solves that problem.