zaro

What is ANSI Escape Code in Java?

Published in Java Console Formatting 5 mins read

ANSI escape codes are a standard mechanism used to control the cursor, color, and other formatting options of text output on terminals and console emulators. In the context of Java, an ANSI escape code is a sequence of characters that, when printed to a compatible console, is interpreted as a command for formatting or control, rather than being displayed as literal text.

Java itself does not have built-in functions or an API specifically designed to generate or interpret ANSI escape codes. Instead, Java applications achieve terminal manipulation by simply printing these special character sequences to the standard output stream (e.g., System.out.print() or System.out.println()). If the terminal emulator running the Java application supports ANSI escape sequences, it will render the output accordingly.

The Structure of ANSI Escape Codes

Most ANSI escape codes begin with the Escape character (represented as \u001b or \033 in Java strings) followed by an opening bracket [ and then a sequence of parameters and a final command character.

For example, \u001b[31m changes the text color to red, and \u001b[0m resets all formatting attributes to their default.

Common Categories of ANSI Escape Codes

ANSI escape codes are broadly categorized by their function:

  • Select Graphic Rendition (SGR): Used for changing text attributes like foreground and background colors, bold, italic, underline, and blinking.
  • Cursor Control: Manipulating the cursor's position (e.g., moving it up, down, left, right, to a specific row/column, saving/restoring its position).
  • Erase Functions: Clearing parts of the screen or line.
  • Screen Modes: Setting terminal modes (less commonly used directly in application output).

Erase Functions

Erase functions are particularly useful for creating dynamic or clean console output by clearing specific areas. The following table details common erase functions:

ESC Code Sequence Description
ESC[2J Erase entire screen
ESC[3J Erase saved lines
ESC[K Erase in line (same as ESC[0K)
ESC[0K Erase from cursor to end of line

Note: To clear the entire screen and move the cursor to the home position (top-left), you often combine ESC[2J with ESC[H (cursor home).

Enabling ANSI Support in Java on Different Operating Systems

The effectiveness of ANSI escape codes depends heavily on the terminal or console environment where the Java program runs:

  • Linux/macOS: Most modern terminals (e.g., Bash, Zsh, iTerm2, Terminal.app) natively support ANSI escape codes, so Java applications will display formatted output without any special configuration.
  • Windows:
    • Newer Versions (Windows 10, Windows 11, PowerShell, Windows Terminal): These environments typically have native support for ANSI escape codes enabled by default.
    • Older Versions (Command Prompt prior to Windows 10 build 10586): The traditional Windows Command Prompt did not support ANSI escape codes natively. For these older environments, developers often used libraries like Jansi (Java ANSI), which detects the operating system and either enables native console support or translates ANSI codes into Windows API calls.

Practical Examples of ANSI Escape Codes in Java

Here are examples demonstrating how to use ANSI escape codes for common console formatting tasks in Java:

public class ConsoleFormatter {

    // ANSI escape codes for colors and reset
    public static final String ANSI_RESET = "\u001b[0m";
    public static final String ANSI_BLACK = "\u001b[30m";
    public static final String ANSI_RED = "\u001b[31m";
    public static final String ANSI_GREEN = "\u001b[32m";
    public static final String ANSI_YELLOW = "\u001b[33m";
    public static final String ANSI_BLUE = "\u001b[34m";
    public static final String ANSI_PURPLE = "\u001b[35m";
    public static final String ANSI_CYAN = "\u001b[36m";
    public static final String ANSI_WHITE = "\u001b[37m";

    // ANSI escape codes for background colors
    public static final String ANSI_BG_RED = "\u001b[41m";
    public static final String ANSI_BG_GREEN = "\u001b[42m";

    // ANSI escape codes for text styles
    public static final String ANSI_BOLD = "\u001b[1m";
    public static final String ANSI_ITALIC = "\u001b[3m";
    public static final String ANSI_UNDERLINE = "\u001b[4m";

    public static void main(String[] args) throws InterruptedException {
        // 1. Changing Text Color
        System.out.println(ANSI_RED + "This text is red." + ANSI_RESET);
        System.out.println(ANSI_GREEN + "This text is green." + ANSI_RESET);
        System.out.println(ANSI_BLUE + "This text is blue." + ANSI_RESET);

        // 2. Applying Text Styles
        System.out.println(ANSI_BOLD + "This text is bold." + ANSI_RESET);
        System.out.println(ANSI_ITALIC + "This text is italic." + ANSI_RESET);
        System.out.println(ANSI_UNDERLINE + "This text is underlined." + ANSI_RESET);
        System.out.println(ANSI_BOLD + ANSI_CYAN + "Bold and Cyan." + ANSI_RESET);

        // 3. Changing Background Color
        System.out.println(ANSI_BG_YELLOW + ANSI_BLACK + "Black text on Yellow background." + ANSI_RESET);
        System.out.println(ANSI_BG_GREEN + ANSI_WHITE + "White text on Green background." + ANSI_RESET);

        // 4. Cursor Control and Erasing
        System.out.println("\n--- Erase Examples ---");

        // Simulate a progress bar by clearing parts of a line
        System.out.print("Loading: [          ]");
        for (int i = 0; i <= 10; i++) {
            System.out.print("\b\b\b\b\b\b\b\b\b\b\b\b\b" + // Move cursor back
                               "\u001b[K" + // Erase from cursor to end of line
                               "Loading: [" + "#".repeat(i) + " ".repeat(10 - i) + "]" +
                               (i * 10) + "%");
            Thread.sleep(200); // Simulate work
        }
        System.out.println("\nLoading complete!");

        // Erase entire screen (and move cursor to top-left)
        System.out.println("\nClearing screen in 3 seconds...");
        Thread.sleep(3000);
        System.out.print("\u001b[2J"); // Erase entire screen
        System.out.print("\u001b[H");  // Move cursor to home position
        System.out.println("Screen cleared!");
        System.out.println("New content starts here.");
    }
}

Considerations

  • Terminal Compatibility: Always be mindful that not all terminal emulators or IDE consoles (like those in IntelliJ IDEA or Eclipse) fully support all ANSI escape codes. Testing your output across different environments is crucial.
  • Resetting Attributes: It's good practice to always reset text attributes using \u001b[0m after applying formatting. This prevents the formatting from "leaking" to subsequent output or other applications running in the same terminal session.
  • Complexity: For very complex console UI, dedicated text UI libraries (like Lanterna or JLine) might be a more robust solution than manually managing escape codes.