CLI 中未应用文本格式 - 使用 PICOCLI java

Text formating is not applied in CLI - using PICOCLI java

我一直在尝试在 CLI 上显示格式化文本。我尝试了 picocli docs (doc link) 中提供的完全相同的代码,但似乎没有应用格式。

请帮我找出错误。

预期输出

我的代码

import java.util.concurrent.Callable;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Help.Ansi;

@Command(name = "test", mixinStandardHelpOptions = true, version = "test 1.0",
   description = "Custom @|bold,underline styles|@ and @|fg(red) colors|@.")
public class Interpreter  implements Callable<Integer> {
    @Override
    public Integer call() throws Exception { // your business logic goes here...
        String str = Ansi.AUTO.string("@|red Hello, colored world!|@");
        System.out.println(str);
        return 0;
    }

    public static void main (String[] args) {
            
        CommandLine prompt = new CommandLine(new Interpreter());
        int exitCode = prompt.execute(args);
        
        System.exit(exitCode);
    }

我的输出(未应用格式)

PS。我正在使用 picocli v 4.5.2,将项目导出为 runnable jar,并将其构建到 .exe 使用 Launch4j。 在 windows 10.

命令提示符下执行结果 exe

要在 Windows 中获得 ANSI 颜色,您需要做一些额外的工作。最好的方法是将 Jansi 库添加到类路径中。

要使用 Jansi,您需要在您的应用程序中启用它:

import org.fusesource.jansi.AnsiConsole;
// ...
public static void main(String[] args) {
    AnsiConsole.systemInstall(); // enable colors on Windows
    new CommandLine(new Interpreter()).execute(args);
    AnsiConsole.systemUninstall(); // cleanup when done
}

如果您有兴趣创建带有 GraalVM (instead of using Launch4j), then be aware that Jansi by itself is insufficient 的本机 Windows CLI 可执行文件以显示颜色。这部分是因为 GraalVM 需要配置,部分是因为 Jansi 在内部依赖于非标准系统属性,如果这些属性不存在(就像 GraalVM 中的情况一样),则无法正常回退。

在解决此问题之前,您可能有兴趣将 Jansi 与 picocli-jansi-graalvm 结合使用。用法示例:

import picocli.jansi.graalvm.AnsiConsole; // not org.fusesource.jansi.AnsiConsole
// ...
public static void main(String[] args) {
    int exitCode;
    try (AnsiConsole ansi = AnsiConsole.windowsInstall()) {
        exitCode = new CommandLine(new Interpreter()).execute(args);
    }
    System.exit(exitCode);
}

另请参阅 ANSI colors in Windows 上的 picocli 用户手册部分。