[java] How to print color in console using System.out.println?

How can I print color in console? I want to show data in colors when the processor sends data and in different colors when it receives data.

This question is related to java text colors

The answer is


Best Solution to print any text in red color in Java is:

System.err.print("Hello World");

Here are a list of colors in a Java class with public static fields

Usage

System.out.println(ConsoleColors.RED + "RED COLORED" +
ConsoleColors.RESET + " NORMAL");


Note Don't forget to use the RESET after printing as the effect will remain if it's not cleared


public class ConsoleColors {
    // Reset
    public static final String RESET = "\033[0m";  // Text Reset

    // Regular Colors
    public static final String BLACK = "\033[0;30m";   // BLACK
    public static final String RED = "\033[0;31m";     // RED
    public static final String GREEN = "\033[0;32m";   // GREEN
    public static final String YELLOW = "\033[0;33m";  // YELLOW
    public static final String BLUE = "\033[0;34m";    // BLUE
    public static final String PURPLE = "\033[0;35m";  // PURPLE
    public static final String CYAN = "\033[0;36m";    // CYAN
    public static final String WHITE = "\033[0;37m";   // WHITE

    // Bold
    public static final String BLACK_BOLD = "\033[1;30m";  // BLACK
    public static final String RED_BOLD = "\033[1;31m";    // RED
    public static final String GREEN_BOLD = "\033[1;32m";  // GREEN
    public static final String YELLOW_BOLD = "\033[1;33m"; // YELLOW
    public static final String BLUE_BOLD = "\033[1;34m";   // BLUE
    public static final String PURPLE_BOLD = "\033[1;35m"; // PURPLE
    public static final String CYAN_BOLD = "\033[1;36m";   // CYAN
    public static final String WHITE_BOLD = "\033[1;37m";  // WHITE

    // Underline
    public static final String BLACK_UNDERLINED = "\033[4;30m";  // BLACK
    public static final String RED_UNDERLINED = "\033[4;31m";    // RED
    public static final String GREEN_UNDERLINED = "\033[4;32m";  // GREEN
    public static final String YELLOW_UNDERLINED = "\033[4;33m"; // YELLOW
    public static final String BLUE_UNDERLINED = "\033[4;34m";   // BLUE
    public static final String PURPLE_UNDERLINED = "\033[4;35m"; // PURPLE
    public static final String CYAN_UNDERLINED = "\033[4;36m";   // CYAN
    public static final String WHITE_UNDERLINED = "\033[4;37m";  // WHITE

    // Background
    public static final String BLACK_BACKGROUND = "\033[40m";  // BLACK
    public static final String RED_BACKGROUND = "\033[41m";    // RED
    public static final String GREEN_BACKGROUND = "\033[42m";  // GREEN
    public static final String YELLOW_BACKGROUND = "\033[43m"; // YELLOW
    public static final String BLUE_BACKGROUND = "\033[44m";   // BLUE
    public static final String PURPLE_BACKGROUND = "\033[45m"; // PURPLE
    public static final String CYAN_BACKGROUND = "\033[46m";   // CYAN
    public static final String WHITE_BACKGROUND = "\033[47m";  // WHITE

    // High Intensity
    public static final String BLACK_BRIGHT = "\033[0;90m";  // BLACK
    public static final String RED_BRIGHT = "\033[0;91m";    // RED
    public static final String GREEN_BRIGHT = "\033[0;92m";  // GREEN
    public static final String YELLOW_BRIGHT = "\033[0;93m"; // YELLOW
    public static final String BLUE_BRIGHT = "\033[0;94m";   // BLUE
    public static final String PURPLE_BRIGHT = "\033[0;95m"; // PURPLE
    public static final String CYAN_BRIGHT = "\033[0;96m";   // CYAN
    public static final String WHITE_BRIGHT = "\033[0;97m";  // WHITE

    // Bold High Intensity
    public static final String BLACK_BOLD_BRIGHT = "\033[1;90m"; // BLACK
    public static final String RED_BOLD_BRIGHT = "\033[1;91m";   // RED
    public static final String GREEN_BOLD_BRIGHT = "\033[1;92m"; // GREEN
    public static final String YELLOW_BOLD_BRIGHT = "\033[1;93m";// YELLOW
    public static final String BLUE_BOLD_BRIGHT = "\033[1;94m";  // BLUE
    public static final String PURPLE_BOLD_BRIGHT = "\033[1;95m";// PURPLE
    public static final String CYAN_BOLD_BRIGHT = "\033[1;96m";  // CYAN
    public static final String WHITE_BOLD_BRIGHT = "\033[1;97m"; // WHITE

    // High Intensity backgrounds
    public static final String BLACK_BACKGROUND_BRIGHT = "\033[0;100m";// BLACK
    public static final String RED_BACKGROUND_BRIGHT = "\033[0;101m";// RED
    public static final String GREEN_BACKGROUND_BRIGHT = "\033[0;102m";// GREEN
    public static final String YELLOW_BACKGROUND_BRIGHT = "\033[0;103m";// YELLOW
    public static final String BLUE_BACKGROUND_BRIGHT = "\033[0;104m";// BLUE
    public static final String PURPLE_BACKGROUND_BRIGHT = "\033[0;105m"; // PURPLE
    public static final String CYAN_BACKGROUND_BRIGHT = "\033[0;106m";  // CYAN
    public static final String WHITE_BACKGROUND_BRIGHT = "\033[0;107m";   // WHITE
}

If anyone is looking for a quick solution, feel free to use the following helper class :)

public class Log {

    public static final String ANSI_RESET = "\u001B[0m";
    public static final String ANSI_BLACK = "\u001B[30m";
    public static final String ANSI_RED = "\u001B[31m";
    public static final String ANSI_GREEN = "\u001B[32m";
    public static final String ANSI_YELLOW = "\u001B[33m";
    public static final String ANSI_BLUE = "\u001B[34m";
    public static final String ANSI_PURPLE = "\u001B[35m";
    public static final String ANSI_CYAN = "\u001B[36m";
    public static final String ANSI_WHITE = "\u001B[37m";

    //info
    public static void i(String className, String message) {
        System.out.println(ANSI_GREEN + className + " : " + message + ANSI_RESET);
    }

    //error
    public static void e(String className, String message) {
        System.out.println(ANSI_RED + className + " : " + message + ANSI_RESET);
    }

    //debug
    public static void d(String className, String message) {
        System.out.println(ANSI_BLUE + className + " : " + message + ANSI_RESET);
    }

    //warning
    public static void w(String className, String message) {
        System.out.println(ANSI_YELLOW + className + " : " + message + ANSI_RESET);
    }

}

USAGE:

Log.i(TAG,"This is an info message");

Log.e(TAG,"This is an error message");

Log.w(TAG,"This is a warning message");

Log.d(TAG,"This is a debug message");

Thanks @whiteFang34 for the ANSI codes.


A fairly portable way of doing it is with the raw escape sequences. See http://en.wikipedia.org/wiki/ANSI_escape_code

[edited for user9999999 on 2017-02-20]

Java doesn't "handle the codes", that's true, but Java outputs what you told it to output. it's not Java's fault that the Windows console treats ESC (chr(27)) as just another glyph (?).

you made me boot into Windows. you owe me, bro


Using color function to print text with colors

Code:

enum Color {

    RED("\033[0;31m"),      // RED
    GREEN("\033[0;32m"),    // GREEN
    YELLOW("\033[0;33m"),   // YELLOW
    BLUE("\033[0;34m"),     // BLUE
    MAGENTA("\033[0;35m"),  // MAGENTA
    CYAN("\033[0;36m"),     // CYAN

    private final String code

    Color(String code) {
        this.code = code;
    }

    @Override
    String toString() {
        return code
    }
}

def color = { color, txt ->
    def RESET_COLOR = "\033[0m"
    return "${color}${txt}${RESET_COLOR}"
}

Usage:


test {
    println color(Color.CYAN, 'testing')
}

Try the following enum :

enum Color {
    //Color end string, color reset
    RESET("\033[0m"),

    // Regular Colors. Normal color, no bold, background color etc.
    BLACK("\033[0;30m"),    // BLACK
    RED("\033[0;31m"),      // RED
    GREEN("\033[0;32m"),    // GREEN
    YELLOW("\033[0;33m"),   // YELLOW
    BLUE("\033[0;34m"),     // BLUE
    MAGENTA("\033[0;35m"),  // MAGENTA
    CYAN("\033[0;36m"),     // CYAN
    WHITE("\033[0;37m"),    // WHITE

    // Bold
    BLACK_BOLD("\033[1;30m"),   // BLACK
    RED_BOLD("\033[1;31m"),     // RED
    GREEN_BOLD("\033[1;32m"),   // GREEN
    YELLOW_BOLD("\033[1;33m"),  // YELLOW
    BLUE_BOLD("\033[1;34m"),    // BLUE
    MAGENTA_BOLD("\033[1;35m"), // MAGENTA
    CYAN_BOLD("\033[1;36m"),    // CYAN
    WHITE_BOLD("\033[1;37m"),   // WHITE

    // Underline
    BLACK_UNDERLINED("\033[4;30m"),     // BLACK
    RED_UNDERLINED("\033[4;31m"),       // RED
    GREEN_UNDERLINED("\033[4;32m"),     // GREEN
    YELLOW_UNDERLINED("\033[4;33m"),    // YELLOW
    BLUE_UNDERLINED("\033[4;34m"),      // BLUE
    MAGENTA_UNDERLINED("\033[4;35m"),   // MAGENTA
    CYAN_UNDERLINED("\033[4;36m"),      // CYAN
    WHITE_UNDERLINED("\033[4;37m"),     // WHITE

    // Background
    BLACK_BACKGROUND("\033[40m"),   // BLACK
    RED_BACKGROUND("\033[41m"),     // RED
    GREEN_BACKGROUND("\033[42m"),   // GREEN
    YELLOW_BACKGROUND("\033[43m"),  // YELLOW
    BLUE_BACKGROUND("\033[44m"),    // BLUE
    MAGENTA_BACKGROUND("\033[45m"), // MAGENTA
    CYAN_BACKGROUND("\033[46m"),    // CYAN
    WHITE_BACKGROUND("\033[47m"),   // WHITE

    // High Intensity
    BLACK_BRIGHT("\033[0;90m"),     // BLACK
    RED_BRIGHT("\033[0;91m"),       // RED
    GREEN_BRIGHT("\033[0;92m"),     // GREEN
    YELLOW_BRIGHT("\033[0;93m"),    // YELLOW
    BLUE_BRIGHT("\033[0;94m"),      // BLUE
    MAGENTA_BRIGHT("\033[0;95m"),   // MAGENTA
    CYAN_BRIGHT("\033[0;96m"),      // CYAN
    WHITE_BRIGHT("\033[0;97m"),     // WHITE

    // Bold High Intensity
    BLACK_BOLD_BRIGHT("\033[1;90m"),    // BLACK
    RED_BOLD_BRIGHT("\033[1;91m"),      // RED
    GREEN_BOLD_BRIGHT("\033[1;92m"),    // GREEN
    YELLOW_BOLD_BRIGHT("\033[1;93m"),   // YELLOW
    BLUE_BOLD_BRIGHT("\033[1;94m"),     // BLUE
    MAGENTA_BOLD_BRIGHT("\033[1;95m"),  // MAGENTA
    CYAN_BOLD_BRIGHT("\033[1;96m"),     // CYAN
    WHITE_BOLD_BRIGHT("\033[1;97m"),    // WHITE

    // High Intensity backgrounds
    BLACK_BACKGROUND_BRIGHT("\033[0;100m"),     // BLACK
    RED_BACKGROUND_BRIGHT("\033[0;101m"),       // RED
    GREEN_BACKGROUND_BRIGHT("\033[0;102m"),     // GREEN
    YELLOW_BACKGROUND_BRIGHT("\033[0;103m"),    // YELLOW
    BLUE_BACKGROUND_BRIGHT("\033[0;104m"),      // BLUE
    MAGENTA_BACKGROUND_BRIGHT("\033[0;105m"),   // MAGENTA
    CYAN_BACKGROUND_BRIGHT("\033[0;106m"),      // CYAN
    WHITE_BACKGROUND_BRIGHT("\033[0;107m");     // WHITE

    private final String code;

    Color(String code) {
        this.code = code;
    }

    @Override
    public String toString() {
        return code;
    }
}

And now we will make a small example:

class RunApp {
    public static void main(String[] args) {

        System.out.print(Color.BLACK_BOLD);
        System.out.println("Black_Bold");
        System.out.print(Color.RESET);

        System.out.print(Color.YELLOW);
        System.out.print(Color.BLUE_BACKGROUND);
        System.out.println("YELLOW & BLUE");
        System.out.print(Color.RESET);

        System.out.print(Color.YELLOW);
        System.out.println("YELLOW");
        System.out.print(Color.RESET);
    }
}

To strikeout:

public static final String ANSI_STRIKEOUT_BLACK = "\u001B[30;9m";
public static final String ANSI_STRIKEOUT_RED = "\u001B[31;9m";
public static final String ANSI_STRIKEOUT_GREEN = "\u001B[32;9m";
public static final String ANSI_STRIKEOUT_YELLOW = "\u001B[33;9m";
public static final String ANSI_STRIKEOUT_BLUE = "\u001B[34;9m";
public static final String ANSI_STRIKEOUT_PURPLE = "\u001B[35;9m";
public static final String ANSI_STRIKEOUT_CYAN = "\u001B[36;9m";
public static final String ANSI_STRIKEOUT_WHITE = "\u001B[37;9m";

I created a library called JColor that works on Linux, macOS, and Windows 10.

It uses the ANSI codes mentioned by WhiteFang, but abstracts them using words instead of codes which is more intuitive. Recently I added support for 8 and 24 bit colors

Choose your format, colorize it, and print it:

System.out.println(colorize("Green text on blue", GREEN_TEXT(), BLUE_BACK()));

You can also define a format once, and reuse it several times:

AnsiFormat fWarning = new AnsiFormat(RED_TEXT(), YELLOW_BACK(), BOLD());
System.out.println(colorize("Something bad happened!", fWarning));

Head over to JColor github repository for some examples.


Emoji

You can use colors for text as others mentioned in their answers.

But you can use emojis instead! for example you can use You can use ?? for warning messages and for error messages.

Or simply use these note books as a color:

: error message
: warning message
: ok status message
: action message
: canceled status message
: Or anything you like and want to recognize immediately by color

Bonus:

This method also helps you to quickly scan and find logs directly in the source code.

But linux and Windows CMD default emoji font is not colorful by default and you may want to make them colorful, first.


If you use Kotlin (which works seamlessly with Java), you can make such an enum:

enum class AnsiColor(private val colorNumber: Byte) {
    BLACK(0), RED(1), GREEN(2), YELLOW(3), BLUE(4), MAGENTA(5), CYAN(6), WHITE(7);

    companion object {
        private const val prefix = "\u001B"
        const val RESET = "$prefix[0m"
        private val isCompatible = "win" !in System.getProperty("os.name").toLowerCase()
    }

    val regular get() = if (isCompatible) "$prefix[0;3${colorNumber}m" else ""
    val bold get() = if (isCompatible) "$prefix[1;3${colorNumber}m" else ""
    val underline get() = if (isCompatible) "$prefix[4;3${colorNumber}m" else ""
    val background get() = if (isCompatible) "$prefix[4${colorNumber}m" else ""
    val highIntensity get() = if (isCompatible) "$prefix[0;9${colorNumber}m" else ""
    val boldHighIntensity get() = if (isCompatible) "$prefix[1;9${colorNumber}m" else ""
    val backgroundHighIntensity get() = if (isCompatible) "$prefix[0;10${colorNumber}m" else ""
}

And then use is as such: (code below showcases the different styles for all colors)

val sampleText = "This is a sample text"
enumValues<AnsiColor>().forEach { ansiColor ->
    println("${ansiColor.regular}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.bold}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.underline}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.background}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.highIntensity}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.boldHighIntensity}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.backgroundHighIntensity}$sampleText${AnsiColor.RESET}")
}

If running on Windows where these ANSI codes are not supported, the isCompatible check avoids issues by replacing the codes with empty string.


If your terminal supports it, you can use ANSI escape codes to use color in your output. It generally works for Unix shell prompts; however, it doesn't work for Windows Command Prompt (Although, it does work for Cygwin). For example, you could define constants like these for the colors:

public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";

Then, you could reference those as necessary.

For example, using the above constants, you could make the following red text output on supported terminals:

System.out.println(ANSI_RED + "This text is red!" + ANSI_RESET);

Update: You might want to check out the Jansi library. It provides an API and has support for Windows using JNI. I haven't tried it yet; however, it looks promising.

Update 2: Also, if you wish to change the background color of the text to a different color, you could try the following as well:

public static final String ANSI_BLACK_BACKGROUND = "\u001B[40m";
public static final String ANSI_RED_BACKGROUND = "\u001B[41m";
public static final String ANSI_GREEN_BACKGROUND = "\u001B[42m";
public static final String ANSI_YELLOW_BACKGROUND = "\u001B[43m";
public static final String ANSI_BLUE_BACKGROUND = "\u001B[44m";
public static final String ANSI_PURPLE_BACKGROUND = "\u001B[45m";
public static final String ANSI_CYAN_BACKGROUND = "\u001B[46m";
public static final String ANSI_WHITE_BACKGROUND = "\u001B[47m";

For instance:

System.out.println(ANSI_GREEN_BACKGROUND + "This text has a green background but default text!" + ANSI_RESET);
System.out.println(ANSI_RED + "This text has red text but a default background!" + ANSI_RESET);
System.out.println(ANSI_GREEN_BACKGROUND + ANSI_RED + "This text has a green background and red text!" + ANSI_RESET);

You could do this using ANSI escape sequences. I've actually put together this class in Java for anyone that would like a simple workaround for this. It allows for more than just color codes.

https://gist.github.com/nathan-fiscaletti/9dc252d30b51df7d710a

(Ported from: https://github.com/nathan-fiscaletti/ansi-util)

Example Use:

StringBuilder sb = new StringBuilder();

System.out.println(
    sb.raw("Hello, ")
      .underline("John Doe")
      .resetUnderline()
      .raw(". ")
      .raw("This is ")
      .color16(StringBuilder.Color16.FG_RED, "red")
      .raw(".")
);

The best way to color console text is to use ANSI escape codes. In addition of text color, ANSI escape codes allows background color, decorations and more.

Unix

If you use springboot, there is a specific enum for text coloring: org.springframework.boot.ansi.AnsiColor

Jansi library is a bit more advanced (can use all the ANSI escape codes fonctions), provides an API and has a support for Windows using JNA.

Otherwise, you can manually define your own color, as shown is other responses.

Windows 10

Windows 10 (since build 10.0.10586 - nov. 2015) supports ANSI escape codes (MSDN documentation) but it's not enabled by default. To enable it:

  • With SetConsoleMode API, use ENABLE_VIRTUAL_TERMINAL_PROCESSING (0x0400) flag. Jansi uses this option.
  • If SetConsoleMode API is not used, it is possible to change the global registry key HKEY_CURRENT_USER\Console\VirtualTerminalLevel by creating a dword and set it to 0 or 1 for ANSI processing: "VirtualTerminalLevel"=dword:00000001

Before Windows 10

Windows console does not support ANSI colors. But it's possible to use console which does.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to text

Difference between opening a file in binary vs text How do I center text vertically and horizontally in Flutter? How to `wget` a list of URLs in a text file? Convert txt to csv python script Reading local text file into a JavaScript array Python: How to increase/reduce the fontsize of x and y tick labels? How can I insert a line break into a <Text> component in React Native? How to split large text file in windows? Copy text from nano editor to shell Atom menu is missing. How do I re-enable

Examples related to colors

is it possible to add colors to python output? How do I use hexadecimal color strings in Flutter? How do I change the font color in an html table? How do I print colored output with Python 3? Change bar plot colour in geom_bar with ggplot2 in r How can I color a UIImage in Swift? How to change text color and console color in code::blocks? Android lollipop change navigation bar color How to change status bar color to match app in Lollipop? [Android] How to change color of the back arrow in the new material theme?