2012-02-06 6 views
9

Esiste un modo indipendente dalla piattaforma con Java per rilevare il tipo di unità su cui si trova un file? Fondamentalmente sono interessato a distinguere tra: dischi rigidi , unità rimovibili (come chiavette USB) e condivisioni di rete. Le soluzioni JNI/JNA non saranno utili. Java 7 può essere assunto.Java: come determinare il tipo di unità su cui si trova un file?

+0

Forse potrebbe essere più semplice da risolvere perché si vuole sapere questo? –

+2

Ho bisogno di queste informazioni per avvisare gli utenti di alcuni inconvenienti del file system sottostante: le prestazioni, il monitoraggio del file system non funziona, cose del genere. – mstrap

+0

Consulta http://stackoverflow.com/questions/3542018/how-can-i-get-list-of-all-drives-but-also-get-the-corresponding-drive-type-remo/17972420#17972420 Sto usando WMI per accedere alle informazioni desiderate. –

risposta

3

La classe FileSystemView dal battente ha alcune funzionalità per supportare rilevare il tipo di azionamento (cf isFloppyDrive, isComputerNode). Temo che non ci sia un modo standard per rilevare se un disco è collegato tramite USB.

forzato, ad esempio non testati:

import javax.swing.JFileChooser; 
import javax.swing.filechooser.FileSystemView; 
.... 
JFileChooser fc = new JFileChooser(); 
FileSystemView fsv = fc.getFileSystemView(); 
if (fsv.isFloppyDrive(new File("A:"))) // is A: a floppy drive? 

In JDK 7 c'è un'altra opzione. Non l'ho usato, ma l'API FileStore ha un metodo type. Il documentation dice che:

Il formato della stringa restituita da questo metodo è altamente specifico di implementazione. Può indicare, ad esempio, il formato utilizzato o se l'archivio file è locale o remoto.

A quanto pare il modo di usarlo sarebbe questo:

import java.nio.*; 
.... 
for (FileStore store: FileSystems.getDefault().getFileStores()) { 
    System.out.printf("%s: %s%n", store.name(), store.type()); 
} 
+4

FileSystemView.isFloppyDrive() è implementato da qualcosa come "path.equals (" A: \\ ")" ciò che sfortunatamente non sarà utile. Inoltre, non ho trovato utile FileStore.type(). Restituisce "NTFS" per le mie condivisioni di rete. – mstrap

+3

FileStore # type() restituisce "NTFS" per le unità di rete su Windows 7, Java 7. –

+0

FileStore # type() restituisce "NTFS" anche per dischi rigidi locali su Windows 10. – simpleuser

1

dare uno sguardo su questa discussione: How can I get list of all drives but also get the corresponding drive type (removable,local disk, or cd-rom,dvd-rom... etc)?

In particolare prestare attenzione sulla http://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/filechooser/FileSystemView.html

Io personalmente non hanno utilizzato questo ma sembra rilevante. Ha il metodo come è isFloppyDrive.

Anche dare un'occhiata su JSmooth

+0

FileSystemView non funzionerà. JSmooth potrebbe funzionare, anche se speravo di trovare qualche API fornita con JRE stesso. – mstrap

4

Si potrebbe eseguire cmd utilizzando Java con:

fsutil fsinfo drivetype {drive letter} 

Il risultato vi darà qualcosa di simile:

C: - Fixed Drive 
D: - CD-ROM Drive 
E: - Removable Drive 
P: - Remote/Network Drive 
+3

Non è indipendente dalla piattaforma e fsutil sembra addirittura richiedere privilegi amministrativi. – mstrap

+1

Ho trovato questo codice molto utile: http://stackoverflow.com/questions/10678363/find-the-directory-for-a-filestore – MAbraham1

+0

anch'io (molto utile) – philwalk

0

Ecco un Gist, che mostra come determinarlo usando net use: https://gist.github.com/digulla/31eed31c7ead29ffc7a30aaf87131def

parte più importante del codice:

public boolean isDangerous(File file) { 
     if (!IS_WINDOWS) { 
      return false; 
     } 

     // Make sure the file is absolute 
     file = file.getAbsoluteFile(); 
     String path = file.getPath(); 
//  System.out.println("Checking [" + path + "]"); 

     // UNC paths are dangerous 
     if (path.startsWith("//") 
      || path.startsWith("\\\\")) { 
      // We might want to check for \\localhost or \\127.0.0.1 which would be OK, too 
      return true; 
     } 

     String driveLetter = path.substring(0, 1); 
     String colon = path.substring(1, 2); 
     if (!":".equals(colon)) { 
      throw new IllegalArgumentException("Expected 'X:': " + path); 
     } 

     return isNetworkDrive(driveLetter); 
    } 

    /** Use the command <code>net</code> to determine what this drive is. 
    * <code>net use</code> will return an error for anything which isn't a share. 
    * 
    * <p>Another option would be <code>fsinfo</code> but my gut feeling is that 
    * <code>net</code> should be available and on the path on every installation 
    * of Windows. 
    */ 
    private boolean isNetworkDrive(String driveLetter) { 
     List<String> cmd = Arrays.asList("cmd", "/c", "net", "use", driveLetter + ":"); 

     try { 
      Process p = new ProcessBuilder(cmd) 
       .redirectErrorStream(true) 
       .start(); 

      p.getOutputStream().close(); 

      StringBuilder consoleOutput = new StringBuilder(); 

      String line; 
      try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()))) { 
       while ((line = in.readLine()) != null) { 
        consoleOutput.append(line).append("\r\n"); 
       } 
      } 

      int rc = p.waitFor(); 
//   System.out.println(consoleOutput); 
//   System.out.println("rc=" + rc); 
      return rc == 0; 
     } catch(Exception e) { 
      throw new IllegalStateException("Unable to run 'net use' on " + driveLetter, e); 
     } 
    } 
Problemi correlati