如何使用 Java 检测 USB 设备的插入和拔出(类似监听)?
不只是笔式驱动器,它也可以是扫描仪或打印机。
试过jUSB,没用
USB Java 库会更多,因为我只需要使用它的一部分。
我需要在我的代码中包含这些行,以便可以通知正在插入和拔出的设备。
Java 中的 USB 支持仅限于第三方库。我没有用过这些,但你可以试试 JUSB
如果您无法通过 USB 库找到解决方案,您总是可以做一些简单的工作并循环遍历所有可能的驱动器号,为每个驱动器号创建一个 File 对象并测试是否可以从中读取。如果插入 USB 存储设备,之前失败的驱动器盘符现在将通过,因此您会知道您有一个新设备。当然,您不知道它是什么类型的设备(即它可能是 CD/DVD)。但正如我所说,这不是一个理想的解决方案。
这里有一个实用工具来证明这一点
import java.io.*;
/**
* Waits for USB devices to be plugged in/unplugged and outputs a message
*/
public class FindDrive
{
/**
* Application Entry Point
*/
public static void main(String[] args)
{
String[] letters = new String[]{ "A", "B", "C", "D", "E", "F", "G", "H", "I"};
File[] drives = new File[letters.length];
boolean[] isDrive = new boolean[letters.length];
// init the file objects and the initial drive state
for ( int i = 0; i < letters.length; ++i )
{
drives[i] = new File(letters[i]+":/");
isDrive[i] = drives[i].canRead();
}
System.out.println("FindDrive: waiting for devices...");
// loop indefinitely
while(true)
{
// check each drive
for ( int i = 0; i < letters.length; ++i )
{
boolean pluggedIn = drives[i].canRead();
// if the state has changed output a message
if ( pluggedIn != isDrive[i] )
{
if ( pluggedIn )
System.out.println("Drive "+letters[i]+" has been plugged in");
else
System.out.println("Drive "+letters[i]+" has been unplugged");
isDrive[i] = pluggedIn;
}
}
// wait before looping
try { Thread.sleep(100); }
catch (InterruptedException e) { /* do nothing */ }
}
}
}
我在下面写了检测USB
import java.io.File;
public class UsbDetection {
public static void main(String[] args) {
//here the usb drive names are named as E,F,G,H in the system
String[] drive_name = new String[]{"E", "F", "G", "H", "I", "J", "K", "L", "M", "N"};
//here we initialize an array for the usb that is to be inserted
File[] usb = new File[drive_name.length];
//if the usb is detected then it is assigned True else False
boolean[] usb_detected = new boolean[drive_name.length];
// in below loop we append :/ to the drive names because E:/ D:/
//and then the corresponding drive is searched with the help of canRead() method
for (int i = 0; i < drive_name.length; ++i) {
usb[i] = new File(drive_name[i] + ":/");
//This method determines whether the program can read the file denoted by the mentioned path name
usb_detected[i] = usb[i].canRead();
}
System.out.println("Insert USB");
detect(usb, drive_name, usb_detected);
}
public static void detect(File[] usb, String[] drive_name, boolean[] usb_detected) {
while (true) {
//the following loop is iterated to find the usb inserted
for (int i = 0; i < drive_name.length; ++i) {
boolean if_detected;
if_detected = usb[i].canRead();
if (if_detected != usb_detected[i]) {
if (if_detected){
System.out.println("USB " + drive_name[i] + " detected ");
}else {
System.out.println("USB " + drive_name[i] + " removed ");
}
usb_detected[i] = if_detected;
}
}
}
}
}