1

我有这个代码:

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 端口。有人可以帮助我吗?

4

1 回答 1

1

评论这一行

LibUsb.freeDeviceList(list, true);

您在使用之前释放设备。

于 2021-06-30T17:28:04.030 回答