Search code examples
javawindowsuniquediskidentifier

Windows 7 & Java: Get Disk-identifier


I have a hdd array with 4 encrypted hard-drives (truecrypt). I recently switched back from 5 years of linux to windows 7 and I find myself confronted with a problem I can't find a solution for. Under linux there was a command called "fdisk" which gives you all running (not mounted!) harddrives plus a unique disk-identifier which doesn't change (something like: Disk Identifier: 00x33f1a3c1). I need that same functionality under Windows, preferably writing the code in java.

cheers

edit:// For clarification, I need the Disk-ID without mounting the Disk!


Solution

  • A solution using VBS.

    import java.io.File;
    import java.io.FileWriter;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    
    public class DiskUtils {
      private DiskUtils() {  }
    
      public static String getSerialNumber(String drive) {
      String result = "";
        try {
          File file = File.createTempFile("realhowto",".vbs");
          file.deleteOnExit();
          FileWriter fw = new java.io.FileWriter(file);
    
          String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
                      +"Set colDrives = objFSO.Drives\n"
                      +"Set objDrive = colDrives.item(\"" + drive + "\")\n"
                      +"Wscript.Echo objDrive.SerialNumber";  
          fw.write(vbs);
          fw.close();
          Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
          BufferedReader input =
            new BufferedReader
              (new InputStreamReader(p.getInputStream()));
          String line;
          while ((line = input.readLine()) != null) {
             result += line;
          }
          input.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return result.trim();
      }
    
      public static void main(String[] args){
        String sn = DiskUtils.getSerialNumber("C");
        javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
             null, sn, "Serial Number of C:",
             javax.swing.JOptionPane.DEFAULT_OPTION);
      }
    }