用Java检测USB驱动器

时间:2010-09-30 14:56:48

标签: java

如何检测USB驱动器何时连接到Windows,Linux或Mac中的计算机?

我在网上看到的唯一方法是迭代驱动器,但我认为没有一种非常好的方法可以做到跨平台(例如Linux中的File.listRoots()只返回“/ “)。即使在Windows中,这也会导致从每个设备读取问题,例如需要很长时间才能访问的网络驱动器。

有一个名为jUsb的库听起来像在Linux中完成了这个,但它在Windows中不起作用。还有一个名为jUsb for Windows的扩展名,但这要求用户安装dll文件并运行.reg。这些似乎都没有发展好几年,所以我希望现在有更好的解决方案。当我只想检测是否连接了包含我需要的文件的设备时,它们对我所需要的东西也有些过分。

[编辑]此外,jUsb显然不适用于任何最新版本的Java,所以这甚至不是一个选项......

由于

6 个答案:

答案 0 :(得分:10)

我已经建立了一个小型库来检测Java上的USB存储设备。它适用于Windows,OSX和Linux。看看:https://github.com/samuelcampos/usbdrivedetector

答案 1 :(得分:8)

上次我检查过没有用于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
  3. 如果你不想搞乱JNI,那么使用任何Windows本机库来获取带有JNA的USB(https://github.com/twall/jna/

    尽管我建议使用WM_DEVICECHANGE方法...因为您的要求只是一条通知消息......

答案 2 :(得分:8)

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

答案 3 :(得分:0)

我写了这个程序。在程序开始时,执行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"));
        }
    }
}

答案 4 :(得分:0)

查看this代码。为了满足您的需求,只需poll即可检测到USB驱动器,并在获得USB驱动器后继续运行。

答案 5 :(得分:-1)

我创建了适用于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*/
           }

      }
 }