Print colored text in consoles (Windows, Mac, Linux)

Home / java / Print colored text in consoles (Windows, Mac, Linux)

Question:
I know this question was asked before, but I have some other questions, too. So, if I use System.err in eclipse, the text is red. But if I do it outside in eclise with the windows command prompt, everything has the same color. Now my question, Is there a way to print colored text in each of these consoles?

I tried it with the following line:System.out.println((char)27 + "[34;43mBlue text with yellow background");

I’ve tried it with Windows 10, didn’t work.

I’ve tried it with Linux Ubuntu, did work, but I don’t no if it works for all Linux variations.

I have no Mac, so unfortunately I can’t try it, but if anybody can try it, help would be nice. (I also don’t to if Mac has this command prompt, so I would thank everybody who can tell me more)

If it’s possible, I would like to make it without any library, but if It is very much easier or without library really really hard, than It’s ok. (And if it’s an library I would be happy If you could tell me what I must do if I want to publish my program that contains this Library).

Thanks, abilnf


Answer:
There is a Java library JANSI to achieve this in Windows by rendering ANSI escape sequences.

Here is how you can use it
import org.fusesource.jansi.AnsiConsole;
import static org.fusesource.jansi.Ansi.*;
import static org.fusesource.jansi.Ansi.Color.*;

public class Sample

{

public static void main(String[] args)
{
AnsiConsole.systemInstall();

System.out.println(ansi().fg(RED).a("Hello World").reset()); // Colored
System.out.println("This is uncolored");

AnsiConsole.systemUninstall();
}
}
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *