Slye
Slye

Reputation: 196

Check if console supports ANSI escape codes in Java

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?

Upvotes: 12

Views: 5263

Answers (2)

trozen
trozen

Reputation: 1273

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.

Upvotes: 9

Fabel
Fabel

Reputation: 1761

I don't know if Java has some special way to deal with this, but there are two ways to deal with the problem itself. The usual method used (at least in the unix world) is to get the terminal used from the TERM environment variable and look up it's capabilities from the terminfo/termcap database (usually using curses or slang). Another more crude approach is to send the Device Status Report code ("\u001B[6n") and check if the terminal responds. This is of course a bit of a hack since a terminal that supports the DSR code might not support color for example.

Upvotes: 4

Related Questions