Home > Java > javaTutorial > How Can I Print Colored Text to the Console Using Java?

How Can I Print Colored Text to the Console Using Java?

Susan Sarandon
Release: 2024-12-25 21:28:09
Original
615 people have browsed it

How Can I Print Colored Text to the Console Using Java?

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
Copy after login

For example:

System.out.println("\u001B[31mThis text is red!\u001B[0m");
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template