Check if console supports ANSI escape codes in Java

ansi-escape, java

Solution

A simple java-only solution:

if (System.console() != null && System.getenv().get("TERM") != null) {
    System.out.println("\u001B[36m"+"Menu option"+"\u001B[0m");
} else {
    System.out.println("Menu option");
}

The first term is there to check if a terminal is attached, second to see if TERM env var is defined (is not on Windows). This isn't perfect, but works well enough in my case.

Problem

I'm building a program in Java that uses menus with different colors using ANSI escape codes. Something like ``` System.out.println("\u001B[36m"+"Menu option"+"\u001B[0m"); ``` The problem is that i want to check if the console where the code is going to be executed supports using this codes, so in case it doesn't, print an alternative version without the codes. It will be something similar to: ``` if(console.supportsANSICode){ System.out.println("\u001B[36m"+"Menu option"+"\u001B[0m"); } else{ System.out.println("Menu option"); } ``` Is there a method in java to check this?

Original source