如何检测USB驱动器何时连接到Windows,Linux或Mac中的计算机?
我在网上看到的唯一方法是迭代驱动器,但我认为没有一种非常好的方法来实现跨平台(例如Linux中的File.listRoots()只返回"/").即使在Windows中,这也会导致从每个设备读取问题,例如需要很长时间才能访问的网络驱动器.
有一个名为jUsb的库听起来像在Linux中完成了这个,但它在Windows中不起作用.还有一个名为jUsb for Windows的扩展名,但这要求用户安装dll文件并运行.reg.这些似乎都没有发展好几年,所以我希望现在有更好的解决方案.当我只想检测设备是否连接包含我需要的文件时,它们对于我需要的东西也是过度的.
[编辑]此外,jUsb显然不适用于任何最新版本的Java,所以这甚至不是一个选项......
谢谢
小智 16
我已经建立了一个小型库来检测Java上的USB存储设备.它适用于Windows,OSX和Linux.看看:https://github.com/samuelcampos/usbdrivedetector
public class AutoDetect {
static File[] oldListRoot = File.listRoots();
public static void main(String[] args) {
AutoDetect.waitForNotifying();
}
public static void waitForNotifying() {
Thread t = new Thread(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (File.listRoots().length > oldListRoot.length) {
System.out.println("new drive detected");
oldListRoot = File.listRoots();
System.out.println("drive"+oldListRoot[oldListRoot.length-1]+" detected");
} else if (File.listRoots().length < oldListRoot.length) {
System.out.println(oldListRoot[oldListRoot.length-1]+" drive removed");
oldListRoot = File.listRoots();
}
}
}
});
t.start();
}
}
Run Code Online (Sandbox Code Playgroud)
上次我检查过没有用于java和Windows的开源USB库.我使用的简单黑客是编写一个小型JNI应用程序来捕获WM_DEVICECHANGE事件.以下链接可能有所帮助
如果你不想搞乱JNI,那么使用任何Windows本机库用于USB和JNA(https://github.com/twall/jna/)
尽管我建议使用WM_DEVICECHANGE方法...因为你的要求只是一个通知消息....
| 归档时间: |
|
| 查看次数: |
29078 次 |
| 最近记录: |