How can I get the serial number of the hard disk with Java?
-
3BTW - if your are doing this to prevent people stealing the software, you've 'already lost'. – Andrew Thompson Mar 30 '11 at 07:13
-
@thompson what do you mean of that comment? – developer Mar 30 '11 at 07:17
-
2he probably means that it is easy to fake the serial number to fool your code. – Stephen C Mar 30 '11 at 07:19
7 Answers
Java runs on a virtual machine which doesn't have hard drives only files and filesystems. You should be able to get this information by running the approriate command line utility from Java.
One Linux you can do
hdparm -i /dev/hda

- 525,659
- 79
- 751
- 1,130
Good news there is a volume:vsn
attribute for the FileStore object.
for (FileStore store: FileSystems.getDefault().getFileStores()) {
System.out.format("%-20s vsn:%s\n", store, store.getAttribute("volume:vsn"));
}
The output looks like an int (e.g. -1037833820
, 194154
)
Bad news it is windows specific for testing purposes as they say in WindowsFileStore jdk8u source. Might work in other platforms and in the future, or not.
Other options (JNI, executing and parsing CLI) are also system dependent. Are more ellaborate but might not suddenly break up when you change the runtime. But I think the attribute solution is much simpler and I am totally going with it until I have something better.

- 678
- 5
- 17
If you are using a Windows OS which is Win7 SP1 or higher, you can simply get it by executing the following cmd command in your java program, via wmic.
wmic diskdrive get serialnumber
If this command returns "Invalid XML content." you may wanna apply the hotfix file as described in here.

- 223
- 1
- 3
- 14
on windows machine you can use
public static String getSerialKey(Character letter) throws Exception{
String line = null;
String serial = null;
Process process = Runtime.getRuntime().exec("cmd /c vol "+letter+":");
BufferedReader in = new BufferedReader(
new InputStreamReader(process.getInputStream()) );
while ((line = in.readLine()) != null) {
if(line.toLowerCase().contains("serial number")){
String[] strings = line.split(" ");
serial = strings[strings.length-1];
}
}
in.close();
return serial;
}

- 3,965
- 2
- 17
- 18
I would imagine you'd have to implement that feature in C or C++ and use JNI to access it from Java.

- 120,358
- 21
- 212
- 242
For a Windows machine you can execute wmic
with parameters and than parse the result like is done in the following snippet:
public static String getNumeroDisq() throws IOException {
Runtime runtime = Runtime.getRuntime();
String[] commands = {"wmic", "diskdrive", "get", "SerialNumber"};
Process process = runtime.exec(commands);
String chain = null;
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String serialNumber= null;
while ((serialNumber = bufferedReader.readLine()) != null) {
if (serialNumber.trim().length() > 0) {
chain = serialNumber;
}
}
return chain.trim();
}
}