views:

3306

answers:

3

I've just started messing around with JLine to parse character input in console mode. It seems to work well, but I'm wondering:

Is there a nonblocking way in JLine to find out if characters are available? (i.e. like kbhit() in Windows.)

I suppose I could always wrap keyboard input in its own thread which then offers the keyboard characters in a thread-safe queue to the main thread, but that seems like it should be unnecessary.

EDIT: This is character-by-character parsing. I am not going to use a GUI. The usual InputStream I/O in Java in console mode requires you to hit the Enter key first (e.g. it's buffered input only). Please don't tell me character-by-character input in console mode is impossible in Java; it isn't. JLine does it using a portable interface with a platform-dependent implementation.

Edit update: I was able to hack together a helper class to do the blocking I/O in a worker thread (using JLine for the per-character I/O, warning: you have to parse Ctrl-C yourself!) & then communicate via a synchronized queue with an isempty() routine. For what I'm doing right now that's fine, but I would really like to know a Good Way To Do This In The Future.

+1  A: 

You can't use a console to get non-blocking input without native libraries.

You'll have to write a Swing app and write a KeyListener

Read this tutorial: http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html

Pyrolistical
A: 

I don't know about JLine, but input to a java console app is not difficult. The following code waits for input from the command line then prints out what you just typed. (after you hit enter)

import java.io.*;
public class Test {
    public static void main (String [] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String input = br.readLine();
            System.out.println(input);
    }
}

Then you can parse the input String.

Ok I understand what you are asking now. I haven't tested it but looking though the 1.6 API this may work.

Console con = System.console();
Reader r = con.reader();

Reader has a method read() to read in a single character, it will still block but only for one character, so you could read in a character do you want you need to do then go back again and wait for the next character input.

Mark Robinson
Didn't work. It does the same, waits for the "enter" to be pressed. :(
OscarRyz
+1  A: 

You seem to be on the right track.

I think the "right" way to do this is a worker thread that pours all the blocking I/O into a non-blocking queue. Hava a look at ConcurrentLinkedQueue from java.util.concurrent.

Ed Brannin