如何为Java输出着色?
例如在C语言和其他语言中,我可以像\033[0m
一样使用ANSI-escape来执行此操作。但是在Java中它不起作用。
public static void main(String[] x) {
System.out.println("\033[0m BLABLA \033[0m\n");
}
答案 0 :(得分:31)
这对我有用:
System.out.println((char)27 + "[31mThis text would show up red" + (char)27 + "[0m");
你需要结束" [37m"将颜色恢复为白色(或您使用的任何颜色)。如果你不这样做,它可能会使所有内容跟随"红色"。
答案 1 :(得分:26)
不,但有第三方API可以处理它
http://www.javaworld.com/javaworld/javaqa/2002-12/02-qa-1220-console.html
编辑:当然有比我发布的文章更新的文章,但信息仍然可行。
答案 2 :(得分:11)
您可以使用JANSI库在Windows中呈现ANSI转义序列。
答案 3 :(得分:10)
是的,这是100%可能的
set classpath =%classpath%; d:\ jansi-1.4.jar;
请尝试以下代码:
import org.fusesource.jansi.AnsiConsole;
import static org.fusesource.jansi.Ansi.*;
import static org.fusesource.jansi.Ansi.Color.*;
public class Sample
{
public static void main(String[] args)
{
AnsiConsole.systemInstall();
System.out.println(ansi().fg(RED).a("Hello World").reset());
System.out.println("My Name is Raman");
AnsiConsole.systemUninstall();
}
}
答案 4 :(得分:5)
以下是Win32控制台的解决方案。
1)在此处获取JavaNativeAccess库:https://github.com/twall/jna/
2)这两个Java类可以解决问题。
享受。
package com.stackoverflow.util;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.Structure;
public class Win32 {
public static final int STD_INPUT_HANDLE = -10;
public static final int STD_OUTPUT_HANDLE = -11;
public static final int STD_ERROR_HANDLE = -12;
public static final short CONSOLE_FOREGROUND_COLOR_BLACK = 0x00;
public static final short CONSOLE_FOREGROUND_COLOR_BLUE = 0x01;
public static final short CONSOLE_FOREGROUND_COLOR_GREEN = 0x02;
public static final short CONSOLE_FOREGROUND_COLOR_AQUA = 0x03;
public static final short CONSOLE_FOREGROUND_COLOR_RED = 0x04;
public static final short CONSOLE_FOREGROUND_COLOR_PURPLE = 0x05;
public static final short CONSOLE_FOREGROUND_COLOR_YELLOW = 0x06;
public static final short CONSOLE_FOREGROUND_COLOR_WHITE = 0x07;
public static final short CONSOLE_FOREGROUND_COLOR_GRAY = 0x08;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_BLUE = 0x09;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_GREEN = 0x0A;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_AQUA = 0x0B;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_RED = 0x0C;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_PURPLE = 0x0D;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_YELLOW = 0x0E;
public static final short CONSOLE_FOREGROUND_COLOR_BRIGHT_WHITE = 0x0F;
public static final short CONSOLE_BACKGROUND_COLOR_BLACK = 0x00;
public static final short CONSOLE_BACKGROUND_COLOR_BLUE = 0x10;
public static final short CONSOLE_BACKGROUND_COLOR_GREEN = 0x20;
public static final short CONSOLE_BACKGROUND_COLOR_AQUA = 0x30;
public static final short CONSOLE_BACKGROUND_COLOR_RED = 0x40;
public static final short CONSOLE_BACKGROUND_COLOR_PURPLE = 0x50;
public static final short CONSOLE_BACKGROUND_COLOR_YELLOW = 0x60;
public static final short CONSOLE_BACKGROUND_COLOR_WHITE = 0x70;
public static final short CONSOLE_BACKGROUND_COLOR_GRAY = 0x80;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_BLUE = 0x90;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_GREEN = 0xA0;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_AQUA = 0xB0;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_RED = 0xC0;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_PURPLE = 0xD0;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_YELLOW = 0xE0;
public static final short CONSOLE_BACKGROUND_COLOR_BRIGHT_WHITE = 0xF0;
// typedef struct _COORD {
// SHORT X;
// SHORT Y;
// } COORD, *PCOORD;
public static class COORD extends Structure {
public short X;
public short Y;
}
// typedef struct _SMALL_RECT {
// SHORT Left;
// SHORT Top;
// SHORT Right;
// SHORT Bottom;
// } SMALL_RECT;
public static class SMALL_RECT extends Structure {
public short Left;
public short Top;
public short Right;
public short Bottom;
}
// typedef struct _CONSOLE_SCREEN_BUFFER_INFO {
// COORD dwSize;
// COORD dwCursorPosition;
// WORD wAttributes;
// SMALL_RECT srWindow;
// COORD dwMaximumWindowSize;
// } CONSOLE_SCREEN_BUFFER_INFO;
public static class CONSOLE_SCREEN_BUFFER_INFO extends Structure {
public COORD dwSize;
public COORD dwCursorPosition;
public short wAttributes;
public SMALL_RECT srWindow;
public COORD dwMaximumWindowSize;
}
// Source: https://github.com/twall/jna/nonav/javadoc/index.html
public interface Kernel32 extends Library {
Kernel32 DLL = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);
// HANDLE WINAPI GetStdHandle(
// __in DWORD nStdHandle
// );
public int GetStdHandle(
int nStdHandle);
// BOOL WINAPI SetConsoleTextAttribute(
// __in HANDLE hConsoleOutput,
// __in WORD wAttributes
// );
public boolean SetConsoleTextAttribute(
int in_hConsoleOutput,
short in_wAttributes);
// BOOL WINAPI GetConsoleScreenBufferInfo(
// __in HANDLE hConsoleOutput,
// __out PCONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo
// );
public boolean GetConsoleScreenBufferInfo(
int in_hConsoleOutput,
CONSOLE_SCREEN_BUFFER_INFO out_lpConsoleScreenBufferInfo);
// DWORD WINAPI GetLastError(void);
public int GetLastError();
}
}
package com.stackoverflow.util;
import java.io.PrintStream;
import com.stackoverflow.util.Win32.Kernel32;
public class ConsoleUtil {
public static void main(String[] args)
throws Exception {
System.out.print("abc");
static_color_print(
System.out,
"def",
Win32.CONSOLE_BACKGROUND_COLOR_RED,
Win32.CONSOLE_FOREGROUND_COLOR_BRIGHT_WHITE);
System.out.print("def");
System.out.println();
}
private static Win32.CONSOLE_SCREEN_BUFFER_INFO _static_console_screen_buffer_info = null;
public static void static_save_settings() {
if (null == _static_console_screen_buffer_info) {
_static_console_screen_buffer_info = new Win32.CONSOLE_SCREEN_BUFFER_INFO();
}
int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
Kernel32.DLL.GetConsoleScreenBufferInfo(stdout_handle, _static_console_screen_buffer_info);
}
public static void static_restore_color()
throws Exception {
if (null == _static_console_screen_buffer_info) {
throw new Exception("Internal error: Must save settings before restore");
}
int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
Kernel32.DLL.SetConsoleTextAttribute(
stdout_handle,
_static_console_screen_buffer_info.wAttributes);
}
public static void static_set_color(Short background_color, Short foreground_color) {
int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
if (null == background_color || null == foreground_color) {
Win32.CONSOLE_SCREEN_BUFFER_INFO console_screen_buffer_info =
new Win32.CONSOLE_SCREEN_BUFFER_INFO();
Kernel32.DLL.GetConsoleScreenBufferInfo(stdout_handle, console_screen_buffer_info);
short current_bg_and_fg_color = console_screen_buffer_info.wAttributes;
if (null == background_color) {
short current_bg_color = (short) (current_bg_and_fg_color / 0x10);
background_color = new Short(current_bg_color);
}
if (null == foreground_color) {
short current_fg_color = (short) (current_bg_and_fg_color % 0x10);
foreground_color = new Short(current_fg_color);
}
}
short bg_and_fg_color =
(short) (background_color.shortValue() | foreground_color.shortValue());
Kernel32.DLL.SetConsoleTextAttribute(stdout_handle, bg_and_fg_color);
}
public static<T> void static_color_print(
PrintStream ostream,
T value,
Short background_color,
Short foreground_color)
throws Exception {
static_save_settings();
try {
static_set_color(background_color, foreground_color);
ostream.print(value);
}
finally {
static_restore_color();
}
}
public static<T> void static_color_println(
PrintStream ostream,
T value,
Short background_color,
Short foreground_color)
throws Exception {
static_save_settings();
try {
static_set_color(background_color, foreground_color);
ostream.println(value);
}
finally {
static_restore_color();
}
}
}
答案 5 :(得分:4)
我创建了一个名为JCDP的jar
库( Java彩色调试打印机)。
对于Linux,它使用WhiteFang提到的ANSI转义码,但是使用单词而不是代码对它们进行抽象,这更加直观。
对于Windows,它实际上包含JAnsi库,但在其上创建了一个抽象层,维护了为Linux创建的直观和简单的界面。
此库已获得MIT License许可,因此请随时使用。
答案 6 :(得分:3)
最简单的方法是在Cygwin控制台中运行你的程序(未修改)。
第二种最简单的方法是在普通的Windows控制台中运行程序(也是未修改的),通过tee.exe(来自Cygwin或Git发行版)管道输出。 Tee.exe将识别转义码并调用适当的WinAPI函数。
类似的东西:
java MyClass | tee.exe log.txt
java MyClass | tee.exe /dev/null
答案 7 :(得分:2)
转义序列必须由SOMETHING解释才能转换为颜色。 java从命令行启动时使用的标准CMD.EXE不支持这一点,因此Java不支持。
答案 8 :(得分:1)
检查这个:我使用带有转义码的ANSI值,它可能不适用于Windows命令提示符,但在IDE和Unix shell中。 你也可以查看“Jansi&#39;用于Windows支持的库here。
System.out.println("\u001B[35m" + "This text is PURPLE!" + "\u001B[0m");
答案 9 :(得分:0)
System.err.println(&#34; Errorrrrrr&#34;)它将在控制台上以红色打印文本。
答案 10 :(得分:0)
我已经编写了一个名为AnsiScape的库,它允许您以更有条理的方式编写彩色输出:
示例:
AnsiScape ansiScape = new AnsiScape();
String colors = ansiScape.format("{red {blueBg Red text with blue background}} {b Bold text}");
System.out.println(colors);
该库还允许您定义自己的&#34;转义类&#34;类似于CSS课程。
示例:
AnsiScapeContext context = new AnsiScapeContext();
// Defines a "class" for text
AnsiClass text = AnsiClass.withName("text").add(RED);
// Defines a "class" for the title used
AnsiClass title = AnsiClass.withName("title").add(BOLD, BLUE_BG, YELLOW);
// Defines a "class" to render urls
AnsiClass url = AnsiClass.withName("url").add(BLUE, UNDERLINE);
// Registering the classes to the context
context.add(text).add(title).add(url);
// Creating an AnsiScape instance with the custom context
AnsiScape ansiScape = new AnsiScape(context);
String fmt = "{title Chapter 1}\n" +
"{text So it begins:}\n" +
"- {text Option 1}\n" +
"- {text Url: {url www.someurl.xyz}}";
System.out.println(ansiScape.format(fmt));
答案 11 :(得分:-3)
这在日食中起作用只是为了把它变成红色,不知道其他地方。
System.err.println(" BLABLA ");