Printing Colored Text in the Console using System.out.println()
Printing data in different colors can be useful for highlighting important information or distinguishing between different types of messages. In most Unix terminals, ANSI escape codes can be used to add color to console text. However, this functionality is not supported in Windows Command Prompt.
Using ANSI Escape Codes
The ANSI escape codes used for coloring text are:
- Reset: \u001B[0m - Black: \u001B[30m - Red: \u001B[31m - Green: \u001B[32m - Yellow: \u001B[33m - Blue: \u001B[34m - Purple: \u001B[35m - Cyan: \u001B[36m - White: \u001B[37m
For example:
System.out.println("\u001B[31mThis text is red!\u001B[0m");
Changing Background Color
Apart from coloring the text, ANSI escape codes can also be used to change the background color:
- Black background: \u001B[40m - Red background: \u001B[41m - Green background: \u001B[42m - Yellow background: \u001B[43m - Blue background: \u001B[44m - Purple background: \u001B[45m - Cyan background: \u001B[46m - White background: \u001B[47m
Combining text and background colors creates great possibilities for emphasizing text.
Note: ANSI escape codes only work in terminals that support them.
Alternative Library
If using JNI is acceptable, the Jansi library offers an alternative Java API for manipulating text colors in the Windows Command Prompt.
These methods allow you to embed color and background changes directly into your console output.
The above is the detailed content of How Can I Print Colored Text to the Console Using Java?. For more information, please follow other related articles on the PHP Chinese website!