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

后端 未结 13 2501
灰色年华
灰色年华 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: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.

提交回复
热议问题