寫作
當需要將內容寫入您的主控台時,您可以隨時使用 JDK 的 System.out
,然後它會直接進入 JDK 自己的流。另一個建議的方式是使用 JLine 的 Terminal
並從那裡取得writer實例。
如果使用目標端點,即consumer,預期不會返回任何內容,則給定的 CommandContext
包含對 Terminal
的引用,並且可以從那裡存取 writer。
CommandRegistration.builder()
.command("example")
.withTarget()
.consumer(ctx -> {
ctx.getTerminal().writer().println("hi");
ctx.getTerminal().writer().flush();
})
.and()
.build();
如果使用 @Command
,您可以存取 CommandContext
並從那裡取得 Terminal
。
@Command
public void example(CommandContext ctx) {
ctx.getTerminal().writer().println("hi");
ctx.getTerminal().writer().flush();
}
可以自動注入 Terminal
以存取其 writer。
@Autowired
Terminal terminal;
@ShellMethod
public void example() {
terminal.writer().println("hi");
terminal.writer().flush();
}