简体   繁体   中英

Detect plugged usb and read its files in linux using java

I've been trying to:

  1. detect a live mounted usb stick
  2. read its files.

Using usb4java, I was able to fulfill part 1. However usb4Java returns devices and I don't see how I could access the device's files.

This is the code that allows the detection (You can find the complete example on: HotPlug example )

public int processEvent(Context context, Device device, int event,
    Object userData) {
  DeviceDescriptor descriptor = new DeviceDescriptor();
  int result = LibUsb.getDeviceDescriptor(device, descriptor);
  if (result != LibUsb.SUCCESS) {
    throw new LibUsbException("Unable to read device descriptor",
        result);
  }
  System.out.format("%s: %04x:%04x%n",
      event == LibUsb.HOTPLUG_EVENT_DEVICE_ARRIVED ? "Connected" :
          "Disconnected",
      descriptor.idVendor(), descriptor.idProduct());
  return 0;
}

For reading files (part 2),

1 - First read the interface and endpoint details which you are already doing

getDeviceDescriptor(Device device, DeviceDescriptor descriptor)

2 - Based on the available endpoints, you can start Synchronous or Asynchronous transfer to read data -

public static int controlTransfer(DeviceHandle handle, ...)  
public static int bulkTransfer(DeviceHandle handle, ...)

Remember that usb4java works on top of libusb.

usb4java example - link
usb4java API reference - link
libusb API reference - link

you can invoke linux shell commands from java. you want to get information about the files on the USB so it has to be mounted else there would be no easy access to the file system structure. if it is automounted you can see the file system via java ie by

Process p = Runtime.getRuntime().exec("ls /media/home/USB_mass_storage_name"); where /media/home/USB_mass_storage_name is the mount point

if it is not mounted you have to mount the USB from java ( How to execute bash command with sudo privileges in Java? )

in Running system commands in Java applications is more information about this and also a way to read the information from the linux command output back into java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM