简体   繁体   中英

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.

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. 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.

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. 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.

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. When you detect a \\r or \\n , execute the command in the buffer and clear it.

If you receive an up or down arrow, send a number of \\b s to System.out equal to the length of the buffer. 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. This will allow the user to delete it, add to it, or just press enter to submit it. This mimics the functionality of bash.

You can also detect a \\t (tab) character and implement a tab-completion function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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