Java's Scanner class: using left- and right buttons with Bash
I'm not too familiar with Linux/Bash, so I can't really find the right terms to search for.
Take the snippet:
public class Main {
public static void main(String[] args) {
java.util.Scanner开发者_运维知识库 keyboard = new java.util.Scanner(System.in);
while(true) {
System.out.print("$ ");
String in = keyboard.nextLine();
if(in.equals("q")) break;
System.out.println(" "+in);
}
}
}
If I run it on my Linux box using Bash, I can't use any of the arrow buttons (I'm only interested in the left
- and right
button, btw). For example, if I type "test" and then try to go back by pressing the left button, ^[[D
appears instead of my cursor going back one place:
$ test^[[D
I've tried the newer Console class as well, but the end result is the same. On Windows' cmd.exe
shell, I don't have this problem.
So, the question is: is there a way to change my Java code so that I can use the arrow keys without Bash transforming them in sequences like ^[[D
but actually move the cursor instead?
I'm hoping that I can solve this on a "programming level". If this is not possible, then I guess I'd better try my luck on Superuser to see if there's something I need to change on my Bash console.
Thanks in advance.
Bash is the shell, not the terminal; from your program you're talking to the terminal. To provide that functionality, bash and many other programs use readline - there appears to be a Java wrapper for it but I've never used it. I'm sure someone else will come along with a more definitive answer.
Another option would be a Java curses library.
精彩评论