Acquiring drive names (as opposed to drive letters) in Java

后端 未结 3 706
天命终不由人
天命终不由人 2020-12-07 01:03

On my Windows machine, my main hard drive has the letter C: and the name \"Local disk\".

To list the drive letters in Java on Windows, the File object has the stati

相关标签:
3条回答
  • 2020-12-07 01:24

    Ah yes, you need to get the FileSystemView object and use getSystemDisplayName. (I once implemented a Filesystem browser in Java).

    It's not perfect though but it will get you the name. From the documentation:

    Name of a file, directory, or folder as it would be displayed in a system file browser. Example from Windows: the "M:\" directory displays as "CD-ROM (M:)" The default implementation gets information from the ShellFolder class.

    0 讨论(0)
  • 2020-12-07 01:25

    Actually to get the drive name (ex. Local Disk) you need to use getSystemTypeDescription. getSystemDisplayName returns the volume name.

    import java.io.File;
    import java.util.Arrays;
    import java.util.List;
    import javax.swing.filechooser.FileSystemView;
    
    public class Test2 {
        public static void main(String args[]){
    
          List <File>files = Arrays.asList(File.listRoots());
          for (File f : files) {
            String s1 = FileSystemView.getFileSystemView().getSystemDisplayName (f);
            String s2 = FileSystemView.getFileSystemView().getSystemTypeDescription(f);
            System.out.println("getSystemDisplayName : " + s1);
            System.out.println("getSystemTypeDescription : " + s2);
          }
          /* output (French WinXP)
    
              getSystemDisplayName : 
              getSystemTypeDescription : Disquette 3½ pouces
    
              getSystemDisplayName : REGA1 (C:)
              getSystemTypeDescription : Disque local
    
              getSystemDisplayName : 
              getSystemTypeDescription : Lecteur CD
    
              getSystemDisplayName : My Book (F:)
              getSystemTypeDescription : Disque local
          */
        }
    }
    
    0 讨论(0)
  • 2020-12-07 01:33

    Using WMI (via JACOB or com4j) is another alternative.

    FileSystemView.getSystemDisplayName does not give you the raw volume label. It is a combination of the drive letter and volume label, with a default in case the label has not been set.

    WMI will give you the raw volume label, plus some other info such is whether the drive is removable (surprisingly FileSystemView.isFloppyDrive() does not tell you this; It does literally mean "is it a floppy disk.")

    0 讨论(0)
提交回复
热议问题