Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if console supports ANSI escape codes in Java

Tags:

java

ansi

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?

like image 869
Slye Avatar asked Dec 09 '16 09:12

Slye


People also ask

Does ANSI work in Eclipse?

ANSI Escape in Console This plugin is not needed starting with Eclipse 2022-09 (4.25) From Eclipse 2022-09 the official Eclipse Console supports ANSI escape sequences: https://www.eclipse.org/eclipse/news/4.25/platfo...

Do ANSI escape sequences work on Windows?

The advantage of using ANSI escape codes is that, today, these are available on most operating systems, including Windows, and you don't need to install third party libraries. These are well suited for simple command line applications. If you need to do complex text graphics check the ncurses library.

How can I remove the ANSI escape sequences from a string in Python?

You can use regexes to remove the ANSI escape sequences from a string in Python. Simply substitute the escape sequences with an empty string using re. sub(). The regex you can use for removing ANSI escape sequences is: '(\x9B|\x1B\[)[0-?]


1 Answers

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.

like image 101
trozen Avatar answered Oct 12 '22 22:10

trozen