How to print color in console using System.out.println?
Asked Answered
N

17

486

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.

Nava answered 23/4, 2011 at 5:52 Comment(1)
If the console support (e.g. Eclipse Java console) customizing color of stdout/stderr, then you can use System.out.println for one color and System.err.println for another color.Florella
H
805

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);
Huberman answered 23/4, 2011 at 5:56 Comment(14)
@Huberman Can you please explain what is the use of RESET if its color is BLACK, at least in my console? Is it like a default or sth.?Cookson
@Boro: the reset code turns off all ANSI attributes set so far, which should return the console to its defaults. It's useful if you don't know the default color or are also using some of the other attributes like background color, font styles, etc.Huberman
jansi is really great! for those who develop in eclipse, i can reccomend this plugin: mihai-nita.net/2013/06/03/eclipse-plugin-ansi-in-console and nice piece of code to enable color if the code isn't being executed in console: if (System.console() == null) System.setProperty("jansi.passthrough", "true");Nadya
@Huberman i am using windows and for some reason it is not workingGilded
@PankajNimgade, read the answer again and you'll maybe notice this: however it doesn't work for Windows command promptAlbaugh
It doesn't work on Windows it you're using cmd or powershell. Instead, you can use another console emulator. For instance, it works successfully with Cmder (cmder.net)Coming
Someone shall notice that when copy pasting these colors into NetBeans will result with one extra slash added by NetBeans... So don't be super mad like me while trying this out :DTorpedo
Doesn't work on eclipse Java version: 2018-12 (4.10.0) console windows during debugging. Indeed I want to output red text, for this purpose you can use System.err.printlnFlorella
@DannyLo Thank you so much for the link to the Eclipse plugin!Pas
As far as I know, it should work with newer versions of windows 10 in conhost too as it supports ansi codes.Sweven
If I have public static final String ANSI_RED = "\u001B[31m"; , how can I later get the color used for this specific String ? something like ANSI_RED.getColor(); ? which I would want to return to me Color.REDFaradmeter
@Faradmeter You could just create an Enum with all the unicode ASNI values.Purr
You can get colour in Windows cmd by running "color"Exciter
For WINDOWS 10 users, you will need to ENABLE_VIRTUAL_TERMINAL_PROCESSING #52768085Criterion
I
188

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
}
Imposture answered 1/8, 2017 at 17:57 Comment(2)
worked great in IntelliJ console, thank you!Breakwater
This is a great answer. It would be nice if someone can edit it for italics too, if supported, for the sake of completeness. thanks!Hubey
M
93

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.

Mauve answered 5/8, 2011 at 14:3 Comment(5)
Nice. Works as expected.Purr
So wonderful! I loved it! Thank you! :)Loader
found it. implementation 'com.diogonunes:JColor:5.5.1'Bova
yup, all versions here mvnrepository.com/artifact/com.diogonunes/JColorMauve
Lovely lib, thanks.Te
D
76

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);
    }
}
Depilatory answered 21/8, 2018 at 8:28 Comment(3)
This is a copy of answer https://mcmap.net/q/25742/-how-to-print-color-in-console-using-system-out-printlnMauve
@Mauve That answer seems to be originally from w3schools and this answer provides the constants as an enum, which in my opinion is cleaner, more modern code and a better practice for holding these constants.Veiling
I agree with you on thatMauve
S
14

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

Surveillance answered 23/4, 2011 at 5:56 Comment(7)
which doesn't work because the Java IO layer does not convert those to colors. System.out.println((char)27 + "[31;1mERROR" + (char)27 + "[0m" only yields "[31;1mERROR[0m" when run from a windows cmd.com as an executable .jarSoybean
the question wasn't tagged windows. the Windows console was never ANSI-compliant that I remember.Surveillance
but the issue is that java isn't handling the codes, regardless of cmd.com's supportSoybean
see edited answer. Java is doing exactly as it's told. the problem is the non-ANSI-compliant console.Surveillance
I have same problemMafala
look at cmder.net ; this console works fine on Windows and allows colored textComing
Maven uses this library to have colour in the console on any Operating system fusesource.github.io/jansiConsecration
O
13

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.

Oralee answered 23/9, 2017 at 3:22 Comment(0)
C
13

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 fonts are not colorful by default and you may want to make them colorful, first.


How to open emoji panel?

mac os: control + command + space

windows: win + .

linux: control + . or control + ;

Crimson answered 15/8, 2020 at 18:25 Comment(4)
this might need UTF or similar support. you are only providing the final results, not the things the coder needs to do for that. the answer might break the box of what the question spanned up.Invalidate
Downvoted, for the reasons mentioned by AlexanderMauve
Added instructions for how to use emojis in different operating systems. @MauveCrimson
@AlexanderStohr I have added some more instructions. please tell me if you find any issues or better than that if you find solutions to complete the answer for the community 🙏Crimson
D
12

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

Features

  • Full source documentation
  • 4-bit color support (16 colors)
  • 8-bit color support (255 colors)
  • 24-bit color support (16.7 million colors)
    • Hexadecimal and 8-bit RGB values supported
  • Support for common formatting
    • hidden text, invert colors, blink, underline, strike-through, dim, bold, italic
  • Ability to strip ANSI from strings containing ANSI escape sequences.

Example Use

System.out.println(

   new AnsiStringBuilder()
       // All formatting functions support at least three different
       // overloads, each intended for a different use case.

       // Use case 1: Manual Reset
       .italic()
       .append("This is italicized and reset manually.")
       // You can optionaly supply an additional append string
       // to any of the reset functions that will be appended
       // after the formating reset has been applied.
       .resetItalic(System.lineSeparator())

       // Use case 2: Automatic Reset
       .dim("This is dimmed and reset automatically.")
       .append(System.lineSeparator())

       // Use case 3: Function Consumer
       .underline(
           sb -> {
               // The string builder passed to this function consumer
               // will automatically wrap all content appended to it
               // with the underline formatting.
               sb.color24(
                   "#00ff00",
                   "This is both underlined and green"
               );
           }
       )
       .append(System.lineSeparator())

);
Disario answered 5/1, 2015 at 21:35 Comment(0)
O
7

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.

Otolaryngology answered 21/1, 2019 at 13:43 Comment(2)
On Windows the Cygwin console does the job. Also when using piplines with e.g. "tee" then the ANSI color codes see interpretation and maybe effects as well. Byond color codes the ANSI escapes can also do e.g. cursor control.Invalidate
No, the variable has to be in the key HKEY_CURRENT_USER\Console directly - do not create another key VirtualTerminalLevel in there.Traject
P
2

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')
}
Poulson answered 5/2, 2020 at 1:55 Comment(0)
H
2

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";
Hymn answered 21/4, 2020 at 11:46 Comment(0)
F
1

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.

Frady answered 20/1, 2019 at 0:53 Comment(0)
W
1

This kotlin code worked for me


import java.io.PrintStream

sealed class BackgroundColor(val value: Int) {
    object Default : BackgroundColor(0)

    // normal colors
    object Black : BackgroundColor(40)
    object Red : BackgroundColor(41)
    object Green : BackgroundColor(42)
    object Yellow : BackgroundColor(43)
    object Blue : BackgroundColor(44)
    object Magenta : BackgroundColor(45)
    object Cyan : BackgroundColor(46)
    object White : BackgroundColor(47)

    // colors with high contrast
    object BlackBright : BackgroundColor(100)
    object RedBright : BackgroundColor(101)
    object GreenBright : BackgroundColor(102)
    object YellowBright : BackgroundColor(103)
    object BlueBright : BackgroundColor(104)
    object MagentaBright : BackgroundColor(105)
    object CyanBright : BackgroundColor(106)
    object WhiteBright : BackgroundColor(107)
}

sealed class TextColor(val value: Int) {
    object Default : TextColor(0)

    // normal colors
    object Black : TextColor(30)
    object Red : TextColor(31)
    object Green : TextColor(32)
    object Yellow : TextColor(33)
    object Blue : TextColor(34)
    object Magenta : TextColor(35)
    object Cyan : TextColor(36)
    object White : TextColor(37)

    // colors with high contrast
    object BlackBright : TextColor(90)
    object RedBright : TextColor(91)
    object GreenBright : TextColor(92)
    object YellowBright : TextColor(93)
    object BlueBright : TextColor(94)
    object MagentaBright : TextColor(95)
    object CyanBright : TextColor(96)
    object WhiteBright : TextColor(97)
}

fun styleOutput(
    backgroundColor: BackgroundColor = BackgroundColor.Default,
    textColor: TextColor = TextColor.Default,
    boldText : Boolean = false,
    italicText : Boolean = false,
    underLineText : Boolean = false,
    action : PrintStream.() -> Unit
) {
    val styleFormat = StringBuilder("${27.toChar()}[${backgroundColor.value};${textColor.value}")

   if (boldText)
       styleFormat.append(";1")

    if (italicText)
        styleFormat.append(";3")

    if (underLineText)
        styleFormat.append(";4")

    styleFormat.append("m")

    print(styleFormat)
    System.out.action()
    print("${27.toChar()}[0m")
}

and to use it

print("text without styling")
styleOutput(backgroundColor = BackgroundColor.Blue, textColor = TextColor.GreenBright, boldText = true) {
    print("text with styling")
}
print("text without styling")
Wetzell answered 11/2, 2022 at 16:54 Comment(0)
M
0

You can use JAnsi dependency to change color in both Linux and Windows. It's prints UTF-8 characters in the right way. https://github.com/fusesource/jansi

Merchandising answered 5/4, 2022 at 7:40 Comment(0)
H
0

Good to konw, e.g. I use Eclipse and the \u033-Prefix-Code does not work. Just use \u001B or \u001b to make it work.

This was shown in the first post but then people switch to "033" without a comment about that their solution ist an alterative way. But thank all af you who posted - that will help!

Maybe it is useful for you :)

Hearts answered 9/11, 2023 at 9:44 Comment(0)
F
0

For Kotlin people:

fun Any.bold(color: String = ""): String = style("$color;1")
fun Any.underline(color: String = ""): String = style("$color;4")
fun Any.style(color: String): String { return "\u001B[${color}m$this\u001B[0m" }

fun Any.colored(fgCol:String, bgCol: String, bold: Boolean = false): String {
  return if(bold) "\u001B[${fgCol};${bgCol};1m$this\u001B[0m"
  else "\u001B[${fgCol};${bgCol}m$this\u001B[0m"
}

Then use it with these constants:

Text Colors
     30     BLACK
     31       RED
     32     GREEN
     33    YELLOW
     34      BLUE
     35   MAGENTA
     36      CYAN
     37     WHITE
 
Background
     40    BLACK
     41      RED
     42    GREEN
     43   YELLOW
     44     BLUE
     45  MAGENTA
     46     CYAN
     47    WHITE
 
High Intensity Text
     90     BLACK
     91       RED
     92     GREEN
     93    YELLOW
     94      BLUE
     95   MAGENTA
     96      CYAN
     97     WHITE


High Intensity backgrounds
     100      BLACK
     101        RED
     102     GREEN
     103    YELLOW
     104      BLUE
     105   MAGENTA
     106      CYAN
     107     WHITE

Usage:

println("yourString".bold("33")) // will print a yellow bold text

To reset the color of the terminal call the style fun with "" as color.

Enjoy!

Female answered 18/12, 2023 at 6:21 Comment(0)
I
-8

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

System.err.print("Hello World");
Invitatory answered 7/11, 2019 at 13:10 Comment(4)
The "downvote" isn't mine - but, there are other answers that provide the OP's question, and they were posted some time ago. When posting an answer see: How do I write a good answer?, please make sure you add either a new solution, or a substantially better explanation, especially when answering older questions.Babbage
@iSahil this probably got downvoted because simply writing to standard error doesn't explicitly color anything. Many IDEs and consoles will interpret error messages and print them in red or similar, but that's not something you can rely on.Korella
While this wasn't the direct answer to the question asked above, this was the answer I was looking for when searching for "java print in red console". Thus, I do feel like it has it's place on this page.Rame
printing to a different output stream just for color will get you in a multitude of problemsSardonic

© 2022 - 2024 — McMap. All rights reserved.