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

后端 未结 13 2315
灰色年华
灰色年华 2020-11-22 05:22

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.

相关标签:
13条回答
  • 2020-11-22 06:16

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

    System.err.print("Hello World");
    
    0 讨论(0)
  • 2020-11-22 06:17

    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.

    0 讨论(0)
  • 2020-11-22 06:17

    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.

    0 讨论(0)
  • 2020-11-22 06:18

    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')
    }
    
    0 讨论(0)
  • 2020-11-22 06:22

    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";
    
    0 讨论(0)
  • 2020-11-22 06:24

    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.

    0 讨论(0)
提交回复
热议问题