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

477

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


2
如果控制台支持(例如Eclipse Java控制台)自定义标准输出/错误输出的颜色,则可以使用System.out.println来设置一种颜色,使用System.err.println来设置另一种颜色。 - jw_
16个回答

1

这段 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")

1
如果您使用与Java无缝协作的Kotlin,您可以创建这样的枚举类型:
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 检查通过将代码替换为空字符串来避免问题。


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

0

0
好的,我知道了,例如我使用Eclipse,但是\u033前缀代码不起作用。只需使用\u001B\u001b即可使其正常工作。
这在第一篇帖子中已经展示过了,但是后来的人们转而使用"033",却没有提到他们的解决方案是另一种方式。但还是要感谢所有发帖的人 - 这将会有所帮助!
也许对你有用 :)

-6
Java中打印任何文本以红色显示的最佳解决方案是:
System.err.print("Hello World");

3
“Downvote”不是我的,但是有其他的答案提供了OP的问题,并且它们是一段时间以前发布的。当发布一个答案时,请确保您添加了一个新的解决方案或者更加详细的解释,特别是在回答老问题时。请参考:如何撰写一个好的答案?(https://stackoverflow.com/help/how-to-answer) - help-info.de
10
这条留言可能因为仅仅将内容写入标准错误输出而被踩。许多集成开发环境和控制台会解释错误信息并以红色或类似颜色打印出来,但这不能作为您依赖的唯一方法。 - David
1
虽然这不是直接回答上面提出的问题,但这正是我在搜索“java print in red console”时寻找的答案。因此,我认为它在这个页面上有它的位置。 - Maude
1
仅为了颜色而将打印输出到不同的输出流将会导致许多问题。 - meredrica

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接