Reputation: 6747
I was recently writing some code that uses File.listRoots()
in Java to get the connected devices when the program starts up. This works perfectly fine in Windows, however I read that it won't work in Linux and I am not a Linux user, so my only access to Linux would be through a university computer which I have no access to at the moment. So I want to ask two thing about this:
First how to get this to be a cross-platform solution for drive detection.
Second how can I "listen" for a device plugging in e.g. a USB plugging in the Computer while the program runs must be "listened" by the program and run an event.
I cannot give any code because it would be really irrelevant and I haven't really implemented much about this feature, so ask away any questions that may need to be answered about my code. I bet that "listening" a device connecting will "listen" a device disconnecting as well, but if this is not the case, I would like to know the solution to this as well.
I work inside a JFrame if that helps at all and I would rather use a native Java package to implement this instead of using some other package IF POSSIBLE even if the native implementation may take much more code and effort!
Note that I use listening within quotes because I know this will probably not be the case as I suspect.
Upvotes: 4
Views: 7230
Reputation: 46
Using the javax.usb library, we can get information about the UsbHostManager, but not easily get devices that are being connected.
import java.util.*;
import javax.usb.*;
public class USBLister {
public static void main(String[] args) throws UsbException {
//Get UsbHub
UsbServices services = UsbHostManager.getUsbServices();
UsbHub root = services.getRootUsbHub();
listPeripherique(root);
}
public static void listPeripherique(UsbHub hub) {
//List all the USBs attached
List perepheriques = hub.getAttachedUsbDevices();
Iterator iterator = perepheriques.iterator();
while (iterator.hasNext()) {
UsbDevice perepherique = (UsbDevice) iterator.next();
System.out.println(perepherique);
if (perepherique.isUsbHub())
listPeripherique((UsbHub) perepherique);
}
}
}
Upvotes: 2
Reputation: 7257
Take a look at JavaHIDAPI
This is a cross-platform Human Interface Device (HID) library that works on Windows, Mac and Linux. It provides all the native libraries for each and has an easy to use interface within Java. Documentation is a little sparse, but it should get you up and running fairly quickly.
In your case you could maintain a background thread that monitors the list of connected devices. When the list changes between one snapshot and the next you can send an event to your application.
Upvotes: 3