首页 > 解决方案 > Linux 从 java 写入 /dev/hidraw2

问题描述

我想/dev/hidraw2在我的java程序中写入。(打开/关闭我的 Buzz 控制器的 LED)

在命令行(在 sudo 模式下)
echo -e "\x00\x00\x00\x00\xff\x00\x00" > /dev/hidraw2
(控制器 3 的 LED = 亮)工作正常。

我想在java中完成同样的事情。

这是我尝试过的:

  public static final //
  void setLEDs(//
      final boolean v1,//
      final boolean v2,//
      final boolean v3,//
      final boolean v4) throws IOException{
    OutputStream out =new BufferedOutputStream (new FileOutputStream("/dev/hidraw2", false));
    // writing to a file looks fine:
    // OutputStream out = new FileOutputStream("/home/test/temp-buzz-leds.t", false);  
    //         cat temp-buzz-leds.t | xxd  -g7 -c7
    //         00000000: 0000ffffffff00  .......

    // working command line example:   echo -e "\x00\x00\xff\xff\xff\xff\x00" > /dev/hidraw2
    byte[] data= new byte[]{(byte)0x00,(byte)0x00,
        (byte)(v1?0xFF:0x00),
        (byte)(v2?0xFF:0x00),
        (byte)(v3?0xFF:0x00),
        (byte)(v4?0xFF:0x00),
        (byte)0x00};
    out.write(data);
    out.flush();      // line 150
    out.close();
  }//end-method

这是我得到的例外:

Exception in thread "main" java.io.IOException: Broken pipe
    at java.io.FileOutputStream.writeBytes(Native Method)
    at java.io.FileOutputStream.write(FileOutputStream.java:326)
    at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
    at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
    at BuzzeControler.setLEDs(BuzzeControler.java:150)
    at BuzzeControler.main(BuzzeControler.java:129)

顺便说一句:通过FileInputStream/dev/hidraw2从java 中读取工作正常。

我希望有编写Linux设备经验的人可以提供帮助。

标签: javalinuxiooutputstream

解决方案


推荐阅读