简体   繁体   English

Java:cli命令的“历史记录”,如何使输出“可编辑”?

[英]Java: “History” for cli commands, how to make ouput “editable”?

I want to add a "history" function to my java programm, like known from bash etc, so pressing the arrow keys should show previous send commands. 我想在我的java程序中添加一个“历史记录”功能,如bash等所知,因此按箭头键应该显示以前的发送命令。

It's no problem to write the past commands to the default output, which will in three new lines if arrow up is hit three times and in not editable output. 将过去的命令写入默认输出是没有问题的,如果向上箭头被击中了3次,它将以新的三行显示,并且在不可编辑的输出中。 I want the output of the programm to be written in the input field so i just have to hit enter, to resend the command. 我希望将programm的输出写在输入字段中,所以我只需要按Enter键即可重新发送命令。

Is this possible? 这可能吗?

Kind Regards 亲切的问候

If you want to roll your own solution, this will get you started. 如果您想推出自己的解决方案,这将帮助您入门。

You want to change from using a buffered input into a direct input. 您想要从使用缓冲输入更改为直接输入。 You can do this by interfacing with System.in directly. 您可以通过直接与System.in接口来实现。 You should create a thread to handle this, and have it block on a call to System.in.read() in a loop, reading one byte at a time. 您应该创建一个线程来处理此问题,并使其在循环中对System.in.read()的调用中阻塞,一次​​读取一个字节。

Each time a byte is read, keep your own buffer updated with the current command that's being read. 每次读取一个字节时,请使用正在读取的当前命令来更新自己的缓冲区。 Every character that gets typed, add it to the buffer. 键入的每个字符都将其添加到缓冲区中。 If the character is a \\b , delete the last character in the buffer. 如果该字符是\\b ,则删除缓冲区中的最后一个字符。 When you detect a \\r or \\n , execute the command in the buffer and clear it. 当您检测到\\r\\n ,请在缓冲区中执行命令并将其清除。

If you receive an up or down arrow, send a number of \\b s to System.out equal to the length of the buffer. 如果您收到向上或向下箭头,请向System.out发送一个等于缓冲区长度的\\b s。 This will erase the local copy of any current command being entered. 这将删除正在输入的任何当前命令的本地副本。 Then print out the new command to System.out and enter it into the buffer, replacing whatever was there. 然后将新命令输出到System.out并将其输入缓冲区,替换其中的任何内容。 This will allow the user to delete it, add to it, or just press enter to submit it. 这将允许用户删除,添加或仅按Enter提交。 This mimics the functionality of bash. 这模仿了bash的功能。

You can also detect a \\t (tab) character and implement a tab-completion function. 您还可以检测\\t (制表符)字符并实现制表符完成功能。

看一下JLine ,它提供命令历史记录,制表符补全和行编辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM