Assume that I am running a process and I want to redirect its streams via the classical technique:
ProcessBuilder pb = new ProcessBuilder("C:/folder/script.bat");
Process p = pb.start();
InputStreamReader out = p.getInputStream();
InputStreamReader err = p.getErrorStream();
OutputStreamWriter in = p.getOutputStream();
Now my question: I want to display all output in black, and all errors in red, and I want to maintain the correct order.
- The first approach that comes to my mind is to use
pb.redirectErrorStream(true);, that merges them in the correct order, but it’s no longer possible to apply the different colors. - The second approach is to just alternatingly check both streams for new output. The problem here is that when output and a error appear at almost the same time, I fail to determine which one should be displayed first. So here I can display the correct colorings, but not in the correct order.
So neither work as expected. How should I display output/errors in different colors, in the correct order?
Your problem is that with your techniques you’re guaranteed to block one or the other stream since you’re listening to both of them on the same thread. You should listen to them on different threads and simply display them when data comes in through them.