使用 java 编程读取 Ubuntu 14.04 鼠标事件文件 (/dev/input/event3) 时出错

Error in reading Ubuntu 14.04 mouse event file (/dev/input/event3) with java programmig

我想通过 java 编程处理 Linux 终端中的鼠标事件。我通过 C++ 和 java 编写了两个程序,它们执行相同的过程。

当我使用c++编程打开和读取文件(“/dev/input/event3”-鼠标事件文件)时,运行宁可执行文件没有问题。 (Ubuntu 14.04 终端和 Ubuntu 服务器 14.04 ---> 没问题)。

但是当我使用 java 编程打开和读取同一个文件时,运行在 Ubuntu 14.04 "java -jar program.jar" 中生成可执行结果文件 "java -jar program.jar" 时出现问题 "terminal"。打开文件没有错误,但是读取文件会出现这样的错误:

java.io.IOException: Invalid argument
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(Unknown Source)
    at eventfileopen.m.main(m.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)

但是当我在 Ubuntu 服务器 14.04 上 运行 相同的 jar 文件时,没有错误,程序运行完美。 我该如何解决这个问题?(问题 = 运行 Ubuntu 14.04 上的 java 程序没有错误。)我猜这个问题与 Ubuntu GUI 和 JDK,但不知道解决这个问题。 我的java程序代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;

public class m {

    public static void main(String[] args) {

        File f = new File("/dev/input/event3");
        FileInputStream is = null;
        try {
            is = new FileInputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        byte[] bytes = new byte[16];
        while(true){
            try 
            {
                is.read(bytes);
            } catch (IOException e) 
            {
                e.printStackTrace();   //-------> error while run on Ubuntu 14.04 and no error on Ubuntu server
            }
            System.out.println(Arrays.toString(bytes));
        }
    }
}

检查您的缓冲区大小是否正确。 最近 Linux input_event 结构的内核大小取决于很多东西,但主要取决于 cpu 架构。这是它的声明:

struct input_event {
      struct timeval time;
      __u16 type;
      __u16 code;
      __s32 value;
};

在 32 位系统上,您的缓冲区大小很可能被接受(16 字节)。

在 64 位系统上,缓冲区很可能不应小于 24 字节。原因是 timeval struct 比 32 位系统占用两倍多 space(多 8 个字节)。

我还没有找到从 Java 获取 input_event 结构大小的可靠方法,我个人为此使用 JNI。