如何使用System.out.println在控制台中打印颜色?

时间:2011-04-23 05:52:54

标签: java text colors

如何在控制台中打印颜色?我想在处理器发送数据时以彩色显示数据,在接收数据时以不同颜色显示数据。

13 个答案:

答案 0 :(得分:488)

如果您的终端支持,您可以使用ANSI escape codes在输出中使用颜色。它通常适用于Unix shell提示;但是,它不适用于Windows命令提示符(虽然,它确实适用于Cygwin)。例如,您可以为颜色定义这些常量:

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";

然后,您可以根据需要引用它们。

例如,使用上述常量,您可以在支持的终端上输出以下红色文本:

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

更新:您可能想查看Jansi库。它提供API并支持使用JNI的Windows。我还没有尝试过;然而,它看起来很有希望。

更新2:此外,如果您希望将文字的背景颜色更改为其他颜色,您也可以尝试以下颜色:

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";

例如:

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);

答案 1 :(得分:44)

我创建了一个名为JCDP的库( Java彩色调试打印机)。

对于Linux,它使用WhiteFang提到的ANSI转义码,但使用词而不是代码来抽象它们,这更加直观。它变得如此简单:

print("Hello World!", Attribute.BOLD, FColor.YELLOW, BColor.GREEN);

对于Windows,它依赖于JAnsi,但在其上创建了一个抽象层,保持了上面显示的直观和简单的API。

您在JCDP's github repository处有一些示例。

答案 2 :(得分:41)

以下是带有public static字段

的Java类中的颜色列表

<强>用法

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


注意  不要忘记在打印后使用RESET因为如果没有清除效果将保留


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
}

答案 3 :(得分:18)

public enum Color {
    //颜色结尾字符串,重置颜色的
    RESET("\033[0m"),

    // Regular Colors 普通颜色,不带加粗,背景色等
    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;
    }
}



    System.out.print(Color.BLACK_BOLD);
    System.out.println("111111111aaaaaaaaaaaaaaaa==============");
    System.out.print(Color.RESET);

    System.out.print(Color.BLUE_BACKGROUND);
    System.out.print(Color.YELLOW); //设置前景色 为YELLOW
    System.out.println("111111111aaaaaaaaaaaaaaaa==============马哥私房菜");
    System.out.println("111111111aaaaaaaaaaaaaaaa==============马哥私房菜");
    System.out.println("111111111aaaaaaaaaaaaaaaa==============马哥私房菜");
    System.out.println("111111111aaaaaaaaaaaaaaaa==============马哥私房菜");
    System.out.print(Color.RESET);

答案 4 :(得分:14)

一种相当便携的方法是使用原始转义序列。见http://en.wikipedia.org/wiki/ANSI_escape_code

[在2017-02-20上为user9999999编辑]

Java没有“处理代码”,这是真的,但Java输出你告诉它输出的内容。 Windows控制台将ESC(chr(27))视为另一个字形(←)不是Java的错。

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

答案 5 :(得分:6)

您可以使用ANSI转义序列执行此操作。我实际上已经把这个类放在Java中,适合那些想要一个简单的解决方法的人。它不仅仅包含颜色代码。

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

(移植自:https://github.com/nathan-fiscaletti/ansi-util

使用示例:

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(".")
);

答案 6 :(得分:5)

如果有人正在寻找快速解决方案,请随意使用以下帮助程序类:)

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");

感谢@ whiteFang34获取ANSI代码。

答案 7 :(得分:4)

表情符号

您可以像其他答案中提到的那样为文本使用颜色。

但是您可以改用表情符号!例如,您可以使用⚠️表示警告消息,而?表示错误消息。

或仅将这些笔记本用作颜色:

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

?奖励:

此方法还可以帮助您快速直接在源代码中直接扫描并查找日志

但是linux和Windows CMD默认的emoji字体默认情况下不是彩色的,您可能首先要使其彩色。

答案 8 :(得分:2)

给控制台文本加上颜色的最佳方法是使用ANSI escape codes。除了文本颜色外,ANSI转义码还允许使用背景颜色,装饰等。

Unix

如果您使用springboot,则有一个用于文本着色的特定枚举:org.springframework.boot.ansi.AnsiColor

Jansi库要先进一点(可以使用所有ANSI转义码功能),提供了一个API,并拥有一个使用JNA的support for Windows

否则,您可以手动定义自己的颜色,如其他响应所示。

Windows 10

Windows 10(自内部版本10.0.10586-2015年11月开始)支持ANSI转义码(MSDN documentation默认情况下未启用。要启用它:

  • 对于SetConsoleMode API,请使用ENABLE_VIRTUAL_TERMINAL_PROCESSING (0x0400)标志。 Jansi使用此选项。
  • 如果未使用SetConsoleMode API,则可以通过创建dword并将其设置为0或1进行ANSI处理来更改全局注册表项HKEY_CURRENT_USER\Console\VirtualTerminalLevel"VirtualTerminalLevel"=dword:00000001

Windows 10之前的版本

Windows控制台不支持ANSI颜色。但是可以使用控制台。

答案 9 :(得分:1)

使用颜色功能来打印带有颜色的文本

代码:

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}"
}

用法:


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

答案 10 :(得分:1)

删除:

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";

答案 11 :(得分:-1)

在Java中以红色打印任何文本的最佳解决方案是:

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

答案 12 :(得分:-2)

如果您使用Kotlin(与Java无缝兼容),则可以创建这样的枚举:

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 ""
}

然后按原样使用:(下面的代码展示了所有颜色的不同样式)

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}")
}

如果在不支持这些ANSI代码的Windows上运行,则isCompatible检查通过将代码替换为空字符串来避免出现问题。