问题描述
我一直试图在 CLI 上显示格式化的文本。我尝试使用 picocli 文档(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 ,将项目导出为可运行 jar ,并使用以下命令将其构建为 .exe 启动4j 。 在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(而不是使用Launch4j)创建本机Windows CLI可执行文件,请注意,Jansi本身就是insufficient来显示颜色。部分原因是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用户手册。