Java colored console output

Java console and terminal color

//Java console color constants public static final String TEXT_RED = «\u001B[31m»; public static final String TEXT_BLACK = «\u001B[30m»; public static final String TEXT_GREEN = «\u001B[32m»; public static final String TEXT_BLUE = «\u001B[34m»; public static final String TEXT_RESET = «\u001B[0m»; public static final String TEXT_PURPLE = «\u001B[35m»; public static final String TEXT_CYAN = «\u001B[36m»; public static final String TEXT_YELLOW = «\u001B[33m»; public static final String TEXT_WHITE = «\u001B[37m»; // Java console color Implementation System.out.println(TEXT_BLUE + «This text is red!» + TEXT_RESET);

Java Terminal color

public static final String ANSI_YELLOW_BACKGROUND = "\u001B[43m"; public static final String ANSI_BLUE_BACKGROUND = "\u001B[44m"; public static final String ANSI_BLACK_BACKGROUND = "\u001B[40m"; public static final String ANSI_PURPLE_BACKGROUND = "\u001B[45m"; public static final String ANSI_CYAN_BACKGROUND = "\u001B[46m"; public static final String ANSI_GREEN_BACKGROUND = "\u001B[42m"; public static final String ANSI_WHITE_BACKGROUND = "\u001B[47m";

public static final String ANSI_YELLOW_BACKGROUND = «\u001B[43m»; public static final String ANSI_BLUE_BACKGROUND = «\u001B[44m»; public static final String ANSI_BLACK_BACKGROUND = «\u001B[40m»; public static final String ANSI_PURPLE_BACKGROUND = «\u001B[45m»; public static final String ANSI_CYAN_BACKGROUND = «\u001B[46m»; public static final String ANSI_GREEN_BACKGROUND = «\u001B[42m»; public static final String ANSI_WHITE_BACKGROUND = «\u001B[47m»;

Источник

Вывод цветного текста в консоль с помощью System.out.println в Java

В обычной практике программирования на Java часто возникает ситуация, когда требуется вывести текст в консоль разными цветами. Это может быть полезно для отслеживания статуса выполнения программы, для разделения типов выводимых данных или для визуального обозначения ошибок.

Читайте также:  Python threading get all threads

Например, в приложении, которое обрабатывает и передает данные, можно было бы выводить входящие данные зеленым цветом, а исходящие – красным. Это существенно упрощает отслеживание процесса обработки данных и делает его более наглядным.

Существует несколько способов вывода цветного текста в консоль в Java. Одним из самых простых является использование управляющих последовательностей ANSI. Это специальные коды, которые интерпретируются терминалом как команды для изменения цвета текста.

Например, для вывода красного текста можно использовать следующий код:

System.out.println("\u001B[31m" + "Красный текст");

В этом примере, «\u001B[31m» – это управляющая последовательность ANSI, которая задает красный цвет текста.

Если нужно изменить цвет фона, то можно использовать другие управляющие последовательности. Например, для установки красного фона используется код «\u001B[41m»:

System.out.println("\u001B[41m" + "Текст на красном фоне");

Важно помнить, что после изменения цвета текста или фона все последующие выводы в консоль будут с этими установками. Чтобы вернуться к стандартным настройкам, нужно использовать управляющую последовательность для сброса – «\u001B[0m»:

System.out.println("\u001B[31m" + "Красный текст" + "\u001B[0m");

В этом примере после вывода красного текста цвет сбрасывается, и все последующие выводы в консоль будут стандартного цвета.

Таким образом, с помощью управляющих последовательностей ANSI можно легко и просто выводить в консоль цветной текст в Java.

Источник

Coloring Java output on the console

Have you ever thought of coloring the output on the console through Java? Well, recently I wanted to color my console output and I’ve got the program working finally after a bit of research.

Just to give you a bit of background about consoles, each console vendor used to have their own standards in the early days. And ANSI had finally introduced a standard for consoles to interpret the colors, positions, control characters etc. You can read more about ANSI escape codes on wiki.

As per the ANSI standard all the instructions to interpret the color and positions should follow below syntax:

  • Output text is the output that should be printed on the console
  • Code represents the effect that should take place on console. Refer below table (Note, I’m giving only very commonly used codes here)

Note: DOS doesn’t support ANSI colors. You can use Linux terminal or Netbeans IDE to run this program. And Escape character in Java is ASCII code 33 (i.e.; \033)

Coloring.java

/** 
* Demonstrating console colring
* @author SANTHOSH REDDY MANDADI
* @version 1.0
* @since 06-June-2013
*/
public class Coloring
public static void main(String args[])
System.out.println("\033[31;1mHello\033[0m, \033[32;1;2mworld!\033[0m");
System.out.println("\033[31mRed\033[32m, Green\033[33m, Yellow\033[34m, Blue\033[0m");
>
>
Hello, world!
Red, Green, Yellow, Blue

Источник

Coloring Java output on the console

Have you ever thought of coloring the output on the console through Java? Well, recently I wanted to color my console output and I’ve got the program working finally after a bit of research.

Just to give you a bit of background about consoles, each console vendor used to have their own standards in the early days. And ANSI had finally introduced a standard for consoles to interpret the colors, positions, control characters etc. You can read more about ANSI escape codes on wiki.

As per the ANSI standard all the instructions to interpret the color and positions should follow below syntax:

  • Output text is the output that should be printed on the console
  • Code represents the effect that should take place on console. Refer below table (Note, I’m giving only very commonly used codes here)

Note: DOS doesn’t support ANSI colors. You can use Linux terminal or Netbeans IDE to run this program. And Escape character in Java is ASCII code 33 (i.e.; \033)

Coloring.java

/** 
* Demonstrating console colring
* @author SANTHOSH REDDY MANDADI
* @version 1.0
* @since 06-June-2013
*/
public class Coloring
public static void main(String args[])
System.out.println("\033[31;1mHello\033[0m, \033[32;1;2mworld!\033[0m");
System.out.println("\033[31mRed\033[32m, Green\033[33m, Yellow\033[34m, Blue\033[0m");
>
>
Hello, world!
Red, Green, Yellow, Blue

Источник

Change font colors in Java console output

The most basic output of most software is text in a console. That’s how most programmers start, a simple «Hello World!» printed in the console. Although not very obvious, it is possible to customize some of the color output and add some style to your program.

To change terminal colors, you just need to add an ANSI code before your string.

One of the most practical way to do that is to create a class that can store static strings with that code, that can be easily imported to your projects. Your strings can have obvious names for better code readability.

Usage

Simply append to the beginning of the string the ANSI color code you want to use.

System.out.println("\u001B[30m" + "Hello World in red!");

Using a Java class

You can search the internet and use the ANSI codes in any way you want. Personally, I like having a class to store static strings to hold the code. It’s very easy to implement:

public class ConsoleColors  public static final String TEXT_RESET = "\u001B[0m"; public static final String TEXT_BLACK = "\u001B[30m"; public static final String TEXT_RED = "\u001B[31m"; public static final String TEXT_GREEN = "\u001B[32m"; public static final String TEXT_YELLOW = "\u001B[33m"; public static final String TEXT_BLUE = "\u001B[34m"; public static final String TEXT_PURPLE = "\u001B[35m"; public static final String TEXT_CYAN = "\u001B[36m"; public static final String TEXT_WHITE = "\u001B[37m"; public static final String TEXT_BRIGHT_BLACK = "\u001B[90m"; public static final String TEXT_BRIGHT_RED = "\u001B[91m"; public static final String TEXT_BRIGHT_GREEN = "\u001B[92m"; public static final String TEXT_BRIGHT_YELLOW = "\u001B[93m"; public static final String TEXT_BRIGHT_BLUE = "\u001B[94m"; public static final String TEXT_BRIGHT_PURPLE = "\u001B[95m"; public static final String TEXT_BRIGHT_CYAN = "\u001B[96m"; public static final String TEXT_BRIGHT_WHITE = "\u001B[97m"; public static final String TEXT_BG_BLACK = "\u001B[40m"; public static final String TEXT_BG_RED = "\u001B[41m"; public static final String TEXT_BG_GREEN = "\u001B[42m"; public static final String TEXT_BG_YELLOW = "\u001B[43m"; public static final String TEXT_BG_BLUE = "\u001B[44m"; public static final String TEXT_BG_PURPLE = "\u001B[45m"; public static final String TEXT_BG_CYAN = "\u001B[46m"; public static final String TEXT_BG_WHITE = "\u001B[47m"; public static final String TEXT_BRIGHT_BG_BLACK = "\u001B[100m"; public static final String TEXT_BRIGHT_BG_RED = "\u001B[101m"; public static final String TEXT_BRIGHT_BG_GREEN = "\u001B[102m"; public static final String TEXT_BRIGHT_BG_YELLOW = "\u001B[103m"; public static final String TEXT_BRIGHT_BG_BLUE = "\u001B[104m"; public static final String TEXT_BRIGHT_BG_PURPLE = "\u001B[105m"; public static final String TEXT_BRIGHT_BG_CYAN = "\u001B[106m"; public static final String TEXT_BRIGHT_BG_WHITE = "\u001B[107m"; >

You can go even further and create some helping methods to output colorful texts in the console. In the following example there are three methods, one to build a string with the AINSI color codes, another that will print a line using the AINSI color codes, and another that will check if the color string parameter is a valid AINSI code.

Note that the methods bellow should be in the same class above. In addition, I’m also using an array called ALL_COLORS, that contains all the color strings, to make validation easier.

 public static boolean isValidColor(String color) for (String checker : ALL_COLORS)  if (color.equals(checker)) return true; > return false; > public static void printColoredLine(String bgColor, String textColor, String toPrint)  System.out.println(buildColoredString(bgColor, textColor, toPrint)); > public static String buildColoredString(String bgColor, String textColor, String str) String toReturn = ""; if (bgColor != null && isValidColor(bgColor)) toReturn += bgColor; if (textColor != null && isValidColor(textColor)) toReturn += textColor; return toReturn + str + TEXT_RESET; >

It’s important to keep in mind that once the color is changed, it will remain as that until your program finishes or you change back to the default or new color.

For that reason, it’s advised to append to the end of your string the ANSI code to return to the default color.

If you want to save even more time, download a copy of this class in here.

Источник

Оцените статью