我如何在控制台打印颜色?当处理器发送数据时,我想用不同的颜色显示数据,当处理器接收数据时,我想用不同的颜色显示数据。
当前回答
您可以使用ANSI转义序列来实现这一点。实际上,我已经在Java中为任何想要简单解决这个问题的人组合了这个类。它允许的不仅仅是颜色代码。
https://gist.github.com/nathan-fiscaletti/9dc252d30b51df7d710a
特性
完整的源代码文档 4位颜色支持(16种颜色) 8位颜色支持(255种颜色) 24位颜色支持(1670万种颜色) 支持十六进制和8位RGB值 支持通用格式 隐藏文本,反转颜色,闪烁,下划线,删除,暗淡,粗体,斜体 能够从包含ANSI转义序列的字符串中剥离ANSI。
示例使用
System.out.println(
new AnsiStringBuilder()
// All formatting functions support at least three different
// overloads, each intended for a different use case.
// Use case 1: Manual Reset
.italic()
.append("This is italicized and reset manually.")
// You can optionaly supply an additional append string
// to any of the reset functions that will be appended
// after the formating reset has been applied.
.resetItalic(System.lineSeparator())
// Use case 2: Automatic Reset
.dim("This is dimmed and reset automatically.")
.append(System.lineSeparator())
// Use case 3: Function Consumer
.underline(
sb -> {
// The string builder passed to this function consumer
// will automatically wrap all content appended to it
// with the underline formatting.
sb.color24(
"#00ff00",
"This is both underlined and green"
);
}
)
.append(System.lineSeparator())
);
其他回答
在Java中用红色打印任何文本的最佳解决方案是:
System.err.print("Hello World");
为控制台文本上色的最好方法是使用ANSI转义码。除了文本颜色,ANSI转义码还允许背景色、装饰色等。
Unix
如果你使用springboot,文本着色有一个特定的enum: org.springframework.boot.ansi.AnsiColor
Jansi库更高级一点(可以使用所有的ANSI转义代码函数),提供了一个API,并支持使用JNA的Windows。
否则,您可以手动定义自己的颜色,如其他响应所示。
Windows 10
Windows 10(自build 10.0.10586 - 2015年11月)支持ANSI转义码(MSDN文档),但默认情况下不启用。启用它:
对于SetConsoleMode API,使用ENABLE_VIRTUAL_TERMINAL_PROCESSING (0x0400)标志。Jansi使用这个选项。 如果没有使用SetConsoleMode API,可以通过创建一个dword来更改全局注册表键HKEY_CURRENT_USER\Console\VirtualTerminalLevel,并将其设置为0或1用于ANSI处理: “VirtualTerminalLevel”= dword: 00000001
Windows 10之前
Windows控制台不支持ANSI颜色。但也可以使用控制台。
这个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")
使用颜色功能打印带有颜色的文本
代码:
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')
}
您可以使用JAnsi依赖项在Linux和Windows中更改颜色。 它以正确的方式打印UTF-8字符。 https://github.com/fusesource/jansi
推荐文章
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何读一个文本文件到一个列表或数组与Python
- 如何找到Java堆大小和内存使用(Linux)?
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 在方法参数中使用NotNull注释
- Spring MVC中处理可选参数的@RequestParam
- Tomcat:如何查找正在运行的Tomcat版本?
- “java”、“javaw”和“javaws”之间有什么区别?
- 将Date对象转换为日历对象
- 在Java中保存最后N个元素的大小有限的队列