I wanted to Print Colored Text in Java Console. I have Ran the following code in VSCode and it Runs fine and its not working in CMD.
The java Code: `
// Java Program to Print Colored Text in Console
// Importing input output classes
import java.io.*;
// Main class
public class GFG {
// Declaring ANSI_RESET so that we can reset the color
public static final String ANSI_RESET = "\u001B[0m";
// Declaring the color
// Custom declaration
public static final String ANSI_YELLOW = "\u001B[33m";
// Main driver method
public static void main(String[] args)
{
// Printing the text on console prior adding
// the desired color
System.out.println(ANSI_YELLOW + "This text is yellow" + ANSI_RESET);
}
}
`
Source: https://www.geeksforgeeks.org/how-to-print-colored-text-in-java-console/
Running the code in windows CMD terminal it shows:
D:\CodeSpaceOfline\sudocu>java sudoco.java
←[31mThis text is yellow←[0m`
ANSI support for the Windows CMD terminal is only available with Windows 10 version 1511 or newer. But even then, it’s not enable by default, for compatibility reasons. Native executables must have been marked as using ANSI or explicitly invoke a dedicated Windows function to enable ANSI support.
Neither applies to
java.exe. Therefore, you don’t get ANSI support.You could work-around this by delegating the printing to another software which has ANSI support enable, like the
echocommand.For large text fragments, you could dump them into a temporary file and use the
typecommand to transfer them to the terminal.Future Java versions will come with support to invoke native functions without the need for native helper code, like a JNI stub. With JDK 19’s preview version, the code to enable ANSI from within Java would look like