- 1 year ago
Get drive letters of USB 3.0 devices (Java under Windows)
To retrieve the drive letters of USB 3.0 devices in Java under Windows, you can use the javax.usb
library, specifically the javax.usb.UsbServices
class. Here's an example:
javaimport javax.usb.*;
import java.util.List;
public class USBDevice {
public static void main(String[] args) {
try {
UsbServices services = UsbHostManager.getUsbServices();
UsbHub rootHub = services.getRootUsbHub();
// Iterate through all USB devices connected to the root hub
List<UsbDevice> devices = rootHub.getAttachedUsbDevices();
for (UsbDevice device : devices) {
// Check if the device is a USB 3.0 device
if (device.getUsbDeviceDescriptor().bcdUSB() >= 0x300) {
// Get the associated USB device descriptor
UsbDeviceDescriptor descriptor = device.getUsbDeviceDescriptor();
// Get the drive letter of the USB device
String driveLetter = descriptor.iSerialNumberString();
System.out.println("USB Device Drive Letter: " + driveLetter);
}
}
} catch (UsbException e) {
e.printStackTrace();
}
}
}
Make sure to include the javax.usb
library in your project's dependencies. You can find the library from various sources, such as the usb4java project (https://usb4java.org/) or the javax-usb-api project on GitHub (https://github.com/nyholku/javax-usb-api).
This code retrieves the root USB hub, iterates through the connected devices, and checks if each device is a USB 3.0 device. If it is, it retrieves the device descriptor and obtains the drive letter associated with the USB device.
Please note that the javax.usb
library requires access to USB devices, which may require elevated permissions or special privileges on the system.