0

如何使用 Java 检测 USB 设备插入和拔出(某种监听)?
不仅仅是笔式驱动器,它也可以是扫描仪或打印机。

我试过jUSB,但它没有用。
USB Java 库会更多,因为我只需要使用一点。

我需要在我的代码中包含这些行,以便可以通知正在插入和拔出的设备。

4

1 回答 1

0

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 */ }

    }
 }
}
于 2017-06-09T09:29:38.630 回答