目录
通过\033特殊转义符实现
这种方法主要适用于Linux系统的控制台,也能在Windows系统中的IDEA中实现,但在Windows系统的控制台中却是乱码。
public class ColourTest {
/**
* @param colour 颜色代号:背景颜色代号(41-46);前景色代号(31-36)
* @param type 样式代号:0无;1加粗;3斜体;4下划线
* @param content 要打印的内容
*/
private static String getFormatLogString(String content, int colour, int type) {
boolean hasType = type != 1 && type != 3 && type != 4;
if (hasType) {
return String.format("\033[%dm%s\033[0m", colour, content);
} else {
return String.format("\033[%d;%dm%s\033[0m", colour, type, content);
}
}
public static void main(String[] args) {
System.out.println("控制台颜色测试:");
System.out.println(getFormatLogString("[ 红色 ]", 31, 0));
System.out.println(getFormatLogString("[ 黄色 ]", 32, 0));
System.out.println(getFormatLogString("[ 橙色 ]", 33, 0));
System.out.println(getFormatLogString("[ 蓝色 ]", 34, 0));
System.out.println(getFormatLogString("[ 紫色 ]", 35, 0));
System.out.println(getFormatLogString("[ 绿色 ]", 36, 0));
}
}
Linux中的测试效果
编译后,在Linux系统上完美运行。

IDEA 中的测试效果
如下图所示,在Windows系统上的 IDEA 中也能实现颜色效果,但请注意 产生颜色的 数字参数 与Linux中的有差异。Linux中同样的代码,在IDEA中运行后的实际颜色是和Linux中有部分不同,比如下图中的绿色。

Windows控制台测试结果
如下图所示,输出乱码,无颜色效果。

通过org.fusesource.jansi实现
这种方法能在Windows控制台和Linux中完美运行,且结果一致,但是在IDEA中没有任何颜色效果。
<dependency>
<groupId>org.fusesource.jansi</groupId>
<artifactId>jansi</artifactId>
<version>2.1.1</version>
</dependency>
Windows控制台测试结果

Linux中的测试效果

IDEA 中的测试效果


