1

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;
}
Majid
  • 654
  • 2
  • 7
  • 28

2 Answers2

2

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

Shaibal
  • 907
  • 8
  • 18
  • I like your answer too but I'm accepting ralf htp's one since it has less dependencies and easier to implement for what I'm looking for. – Majid Jun 28 '17 at 20:21
  • Sure Majid. Glad you got your reply. I focused more on "Reading raw data" instead of "Reading mounted file system" as you used getDeviceDescriptor API which gave me impression that you want to read the data using the USB transfers. – Shaibal Jun 29 '17 at 05:02
2

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 i.e. 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

ralf htp
  • 9,149
  • 4
  • 22
  • 34