usb4java USB错误4:无法打开USB设备:没有这样的设备(可能已断开连接)

时间:2016-06-02 08:42:34

标签: usb4java

我有这段代码:

package prospa8wusb;

import javax.swing.JOptionPane;

import org.usb4java.Device;
import org.usb4java.DeviceDescriptor;
import org.usb4java.DeviceHandle;
import org.usb4java.DeviceList;
import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;

public class Test {
    public static short VENDOR_ID = (short)0x04B8;
    public static short PRODUCT_ID = (short)0x0005;

    public static void main(String[] args) {
        LibUsb.init(null) ;
    Device device=findDevice(VENDOR_ID,PRODUCT_ID);

    DeviceHandle handle = new DeviceHandle();
    int result = LibUsb.open(device, handle);
    if (result != LibUsb.SUCCESS) throw new LibUsbException("Unable to open USB device", result);
    try
    {
        // Use device handle here
    }
    finally
    {
        LibUsb.close(handle);
    }

    }
    public static Device findDevice(short vendorId, short productId)
    {
        // Read the USB device list
        DeviceList list = new DeviceList();
        int result = LibUsb.getDeviceList(null, list);
        if (result < 0) throw new LibUsbException("Unable to get device list", result);

        try
        {
            // Iterate over all devices and scan for the right one
            for (Device device: list)
            {
                DeviceDescriptor descriptor = new DeviceDescriptor();
                result = LibUsb.getDeviceDescriptor(device, descriptor);
                if (result != LibUsb.SUCCESS) throw new LibUsbException("Unable to read device descriptor", result);
                if (descriptor.idVendor() == vendorId && descriptor.idProduct() == productId)

                    JOptionPane.showMessageDialog(null, "ok");
                    return device;
            }
        }
        finally
        {
            // Ensure the allocated device list is freed
            LibUsb.freeDeviceList(list, true);
        }

        System.out.println("Device not found");
        return null;

    }   
}

我收到此错误: USB错误4:无法打开USB设备:没有此类设备(可能已断开连接) 虽然我要通信的usb打印机连接到usb端口。 有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

评论这一行

LibUsb.freeDeviceList(list, true);

您在使用之前释放了设备。