Search code examples
javaansi-colors

How to use System.out.format with colorized text


I want to colorize a formatted output. But the format of the colorized text is ignored:

String leftAlignFormat = "| %-15s | %-15s |";
System.out.format(leftAlignFormat, "\033[38;5;16;48;5;40mHello\033[0m", "World");
| Hello | World           |

The word Hello is correctly colored, but why is the word Hello not correctly formatted?


Solution

  • Java's APIs don't natively understand ANSI color escape codes, so the format(...) API is counting those as characters in the string.

    But when those characters written to an ANSI terminal, the escape codes do not move the cursor, so the formatting appears incorrect.

    Depending on the complexity of the usecase, you will need to build your own wrapper APIs (if there are strings with several colors), or you can work around it by knowing exactly how many extra characters you add to generate a color, and increase your padding width accordingly. For simplicity, I would recommend always prepending the color code sequence and appending the reset, so the "extra" padding is a fixed amount.

    Also keep in mind that ANSI escape codes are not portable, so you may need to support a no color code & template path, depending on your target execution environment(s)