2010-09-30 60 views
21

¿Cómo puedo detectar cuando una unidad USB está conectada a una computadora en Windows, Linux o Mac?Detectar unidad USB en Java

La única forma que he visto en línea para hacer esto es iterar las unidades, pero no creo que haya una manera muy buena de hacerlo en varias plataformas (por ejemplo, File.listRoots() en Linux solo devuelve "/"). Incluso en Windows, esto causaría problemas para leer desde cada dispositivo, como una unidad de red que tarda mucho tiempo en acceder.

Hay una biblioteca llamada jUsb que parece que logra esto en Linux, pero no funciona en Windows. También hay una extensión a esto llamada jUsb para Windows, pero eso requiere que los usuarios instalen un archivo dll y ejecuten un .reg. Ninguno de estos parece haberse desarrollado durante varios años, por lo que espero que exista una mejor solución ahora. También son excesivos para lo que necesito, cuando solo quiero detectar si un dispositivo está conectado que contiene un archivo que necesito.

[Editar] Por otra parte, JUSB aparentemente no funciona con cualquier versión reciente de Java, así que esto no es ni siquiera una opción ...

Gracias

Respuesta

8

Que yo sepa no hubiera abierto fuente de biblioteca USB para Java y en Windows. El truco simple que utilicé fue escribir una pequeña aplicación JNI para capturar el evento WM_DEVICECHANGE. Siguientes enlaces pueden ayudar a

  1. http://www.codeproject.com/KB/system/DriveDetector.aspx
  2. http://msdn.microsoft.com/en-us/library/aa363480(v=VS.85).aspx

En caso de que no quiere meterse con el JNI a continuación, utilizar todas las ventanas de la biblioteca nativo para USB con JNA (https://github.com/twall/jna/)

aunque sugeriría usar el enfoque WM_DEVICECHANGE ... porque su requisito es solo un mensaje de notificación ....

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

El segundo párrafo de la pregunta describe específicamente por qué no se desea este enfoque. – VGR

-1

creé el código que funciona en Linux y Windows Compruebe este

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

     } 
} 
+0

Esto es completamente incorrecto para Windows, se repite sin fin y no hace nada ... – BullyWiiPlaza

0

me escribió este programa. Al comienzo del programa, haga DriverCheck.updateDriverInfo(). Luego, para verificar si un usb ha sido enchufado a o extraído, use DriverChecker.driversChangedSinceLastUpdate() (devuelve boolean).

Para comprobar si se ha insertado un usb, use newDriverDetected(). Para comprobar si se ha eliminado un usb, use driverRemoved()

Esto prácticamente comprueba todas las unidades de disco desde A:/hasta Z: /. La mitad de ellos ni siquiera puede existir, pero de todos modos los verifico.

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")); 
     } 
    } 
} 
0

Echa un vistazo this código. Para cumplir con sus demandas, simplemente poll para detectar el disco USB y continuar cuando lo tenga.

Cuestiones relacionadas