Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java capture process output with color

Tags:

java

cmd

Is there a way to capture console output from a process with color formatting data? Currently I am capturing just the text output with:

ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "mvn dependency:resolve");
// mvn dependency:resolve is an example of a process that outputs color
Process p = builder.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) 
{
   System.out.println(line);
}

But I can't find a way to capture color data for this text. The colored text does not seem to start with any special character or anything.

I am printing this captured text to UI for the user to see log of this process but it is hard to read so I would like to copy the colors from the console.

Here is an example of how it can be done in Go, but can this be done in Java?

This application is going to be run on Windows but it would be great if it could also work on Linux or MacOS by reading the same color data from Shell or Bash.

like image 220
František Jeřábek Avatar asked Aug 21 '17 04:08

František Jeřábek


1 Answers

The problem you are facing doesn't relate strictly to Java capability.

What happens is that many programs check whether stdin is a terminal or a pipe and generate output differently, dropping color formatting for example. Sometimes workaround exists directly by use of special option to force the generation of those color formatting 1.

If this is not available in the binary you are using, the apprently only solution is to write your own pseudo-tty making the targeted binary think it talks to a regular tty.

You can try to use the code presented here 2 or you can take a look at JetBrains/pty4j and see if you can tweak it to your needs.

java output color tty

like image 51
nvidot Avatar answered Oct 03 '22 07:10

nvidot