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


当前回答

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

代码:

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

其他回答

这个kotlin代码对我有用


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

然后使用它

print("text without styling")
styleOutput(backgroundColor = BackgroundColor.Blue, textColor = TextColor.GreenBright, boldText = true) {
    print("text with styling")
}
print("text without styling")

失败:

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

如果你使用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 ""
}

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

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检查通过将代码替换为空字符串来避免问题。

如果有人正在寻找一个快速的解决方案,请随意使用以下helper类:)

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

}

用法:

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代码。

您可以使用JAnsi依赖项在Linux和Windows中更改颜色。 它以正确的方式打印UTF-8字符。 https://github.com/fusesource/jansi