在Java中检测USB驱动器

26

如何在Windows、Linux或Mac计算机上检测USB驱动器的插入?

我看过的唯一在线解决方案是迭代驱动器,但我认为跨平台没有一个很好的方法来实现这一点(例如,在Linux中,File.listRoots()只返回“/”)。即使在Windows中,如果要从每个设备读取,这也会导致访问需要很长时间的网络驱动器等问题。

有一个名为jUsb的库,听起来像是可以在Linux下完成这个任务,但它无法在Windows中工作。还有一个名为jUsb for Windows的扩展,但它需要用户安装dll文件和运行.reg文件。这些似乎都已经多年没有更新,因此我希望现在存在更好的解决方案。当我只想检测是否连接了包含我需要的文件的设备时,它们也过于繁琐。

[编辑] 此外,据说jUsb无法与任何最新版本的Java配合使用,所以这根本不是一个选项……

谢谢

5个回答

21

完美,这个可以胜任 :) - BullyWiiPlaza
@samuelcampos,你能构建一个1.6版本的jar包吗? - Neo Pham
我正在使用一些Java 1.6中没有的功能,而且我不打算降级Java版本。你可以fork这个项目并修复编译错误。这应该不难做到。 - samuelcampos
那么你是如何做到的呢?我正在尝试找到一种连接USB设备的方法,但找不到任何资源。我想自己制作库,而不使用Usb4Java。 - Jonathan J. Pecany

12
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();
}
}

4
问题的第二段具体描述了为什么不希望采用这种方法。 - VGR

9
上次我查看时,没有针对Java和Windows的开源USB库。我使用的简单技巧是编写一个小的JNI应用程序来捕获WM_DEVICECHANGE事件。以下链接可能会有所帮助:
  1. http://www.codeproject.com/KB/system/DriveDetector.aspx
  2. http://msdn.microsoft.com/en-us/library/aa363480(v=VS.85).aspx
如果您不想使用JNI,则可以使用任何Windows本地库与JNA一起使用USB( https://github.com/twall/jna/ )。
尽管我建议使用WM_DEVICECHANGE方法...因为您的要求只是一个通知消息...

-2
我写了这个程序。在程序开始时,执行 DriverCheck.updateDriverInfo()。然后,要检查USB是否已插入拔出,请使用DriverChecker.driversChangedSinceLastUpdate()(返回boolean)。
要检查USB是否已插入,请使用newDriverDetected()。 要检查USB是否已移除,请使用driverRemoved()
这基本上检查从A:/到Z:/的所有磁盘驱动器。其中一半甚至可能不存在,但我仍然对它们进行了检查。
package security;

import java.io.File;

public final class DriverChecker {
    private static boolean[] drivers = new boolean[26];

    private DriverChecker() {

    }

    public static boolean checkForDrive(String dir) {
        return new File(dir).exists();
    }

    public static void updateDriverInfo() {
        for (int i = 0; i < 26; i++) {
            drivers[i] = checkForDrive((char) (i + 'A') + ":/");
        }
    }

    public static boolean newDriverDetected() {
        for (int i = 0; i < 26; i++) {
            if (!drivers[i] && checkForDrive((char) (i + 'A') + ":/")) {
                return true;
            }
        }
        return false;
    }

    public static boolean driverRemoved() {
        for (int i = 0; i < 26; i++) {
            if (drivers[i] && !checkForDrive((char) (i + 'A') + ":/")) {
                return true;
            }
        }
        return false;
    }

    public static boolean driversChangedSinceLastUpdate() {
        for (int i = 0; i < 26; i++) {
            if (drivers[i] != checkForDrive((char) (i + 'A') + ":/")) {
                return true;
            }
        }
        return false;
    }

    public static void printInfo() {
        for (int i = 0; i < 26; i++) {
            System.out.println("Driver " + (char) (i + 'A') + ":/ "
                    + (drivers[i] ? "exists" : "does not exist"));
        }
    }
}

-2

我创建了可以在Linux和Windows上运行的代码,请查看。

 import java.io.BufferedReader; 
 import java.io.File;
 import java.io.IOException;
 import java.io.InputStreamReader;

 public class Main{
 public static void main(String[] args) throws IOException{//main class
     Main m = new Main();//main method
     String os = System.getProperty("os.name").toLowerCase();//get Os name
     if(os.indexOf("win") > 0){//checking if os is *nix or windows
         //This is windows
         m.ListFiles(new File("/storage"));//do some staf for windows i am not so sure about '/storage' in windows
         //external drive will be found on 
     }else{
         //Some *nix OS
         //all *nix Os here
         m.ListFiles(new File("/media"));//if linux removable drive found on media
         //this is for Linux

     }


 }

 void ListFiles(File fls)//this is list drives methods
             throws IOException {
     while(true){//while loop


 try {
    Thread.sleep(5000);//repeate a task every 5 minutes
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
     Process p = Runtime.getRuntime().exec("ls "+fls);//executing command to get the output
     BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));//getting the output
             String line;//output line
                while((line = br.readLine()) != null){//reading the output
                 System.out.print("removable drives : "+line+"\n");//printing the output
           }
          /*You can modify the code as you wish. 
          * To check if external storage drivers pluged in or removed, compare the lenght
          * Change the time interval if you wish*/
           }

      }
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接