javalinuxkeyboard

Tell java which keyboard to listen to


I have one keyboard plugged into a linux box and then I'm running my Java over ssh. I want to know if there is a way to tell Java to listen for input from a specific keyboard/terminal. Since the keyboard I want to capture is plugged into the physical machine and no user is logged in I'm not sure there is a way to do this, but I thought I might ask here?


Solution

  • If you have root permissions you can read keyboard events directly from the keyboard device under /dev/input. Decoding the events will require a little effort but it can be done; you can read about the data format in /dev/input keyboard format.

    This snippet reads keyboard events and recognizes which key A-Z you press and release:

        // replace path with path from your system
        DataInputStream in = new DataInputStream(
            new FileInputStream("/dev/input/by-id/usb-0430_0005-event-kbd"));
        String map = "    abcdefghijlkmnopqrstuvwxyz                                                                                                                                                                                                                                                                ";
        // sizeof(struct timeval) = 16
        byte[] timeval = new byte[16];
        short type, code;
        int value;
        while (true) {
            in.readFully(timeval);
            type = in.readShort();
            code = in.readShort();
            value = in.readInt();
            System.out.printf("%04x %04x %08x %c\n", type, code, value, 
                                                     map.charAt(value>>>24));
        }