Home > Software Development > Writing Colorful Console Output in Java

Writing Colorful Console Output in Java

October 20th, 2013 Leave a comment Go to comments

Almost all of the Java console application I had seen were boring black background and white fonts on Windows. This can be changed using a small Java library called Jansi which is open sourced under Apache 2.0. The download link can be found at its project home. The source code is also available on Github here.

The trick behind the library is the ANSI escape code standard. It basically defines a number of escape codes for terminal operations and changing the font colors. In some way, you can think it as html tags when it comes to color texts.

Time to learn how to "Google" and manage your VMware and clouds in a fast and secure

HTML5 App

Although the result looks great, I did find it’s difficult to use without a complete and working sample. It took me hours to get a good sample code snippet by huyunhjl who had cloned the Jansi library. After reading the short introduction, I found the library is actually quite easy to use.

To enable/disable the ANSI capability, you would need to install/uninstall it with a static method:

AnsiConsole.systemInstall();
...
AnsiConsole.systemUninstall();

Besides the full API version for changing the color, there is an alternative way with mark up like @|red etc.

System.out.println( ansi().eraseScreen().render("@|red Hello|@ @|green World|@") );

The following is a quick HelloWorld example. Note: To see the result, you got to run it in a console, not in IDE which does allow you to print out messages.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import org.fusesource.jansi.AnsiConsole;
import static org.fusesource.jansi.Ansi.*;
import static org.fusesource.jansi.Ansi.Color.*;
 
/**
 * @author Steve Jin (http://www.doublecloud.org)
 */
public class ShowColorText
{
  public static void main(String[] args)
  {
    AnsiConsole.systemInstall();
 
    System.out.println(ansi().eraseScreen().fg(RED).a("Hello").fg(YELLOW).a(" World").reset());
    System.out.println( ansi().eraseScreen().render("@|red Hello|@ @|yellow World|@") );
 
    AnsiConsole.systemUninstall();
  }
}

If you use Maven, you can add the following dependency in your pom.xml file:

    <dependency>
      <groupId>org.fusesource.jansi</groupId>
      <artifactId>jansi</artifactId>
      <version>1.11</version>
    </dependency>
Categories: Software Development Tags: ,