views:

128

answers:

2

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.

+2  A: 

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.

Jefromi
Ah, I see. Thanks for the info Jefromi! I'm going to look into that Java Readline library.
Bart Kiers
+1  A: 

Another option would be a Java curses library.

Dennis Williamson
Tanks Dennis. While *Googling* a bit on the terms "Java" and "readline", I found a library that looks like it suits my needs: jline, which looks to be similar to your suggested library.
Bart Kiers