Check if console supports ANSI escape codes in Java

只谈情不闲聊 提交于 2021-01-27 04:18:31

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/41057014/check-if-console-supports-ansi-escape-codes-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!