获取磁盘序列号
在java下获取windows系统中的磁盘序列号,废话少说直接上代码。
/**
* 获取windows硬盘序列号
* @param drive
* @return 硬盘序列号
*/
public static String getWinHardiskSn(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){
if(Config.DEBUG){
e.printStackTrace();
}
}
return result.trim();
}
在以上代码中使用了cscript工具获取。CScript 是小型C语言
编译器,它的语法和C语言语法很接近,因此 CScript 的
源代码也可以用其他 C/C++编译器进行编译,例如Visual C++.CScript 可以生成
中间代码和
机器码.机器码可以在 CScript IDE 中直接运行,也可以用来生成 EXE
可执行文件.CScript 支持调用DLL和COM(Component Object Model),它可以用来编写OpenGL 和 DirectX 程序.另外您可以使用CScript
编程接口在您自己的程序中增加对C语言
脚本的支持。
以上是在windows系统中获取磁盘序列好的方法,在linux系统中执行
hdparm -i /dev/sda1
命令获取磁盘序列号,不过要root权限。在windows系统不涉权限问题(但有些杀毒软件和防火墙会对程序进行拦截)。
获取磁盘大小信息
磁盘大小信息是不涉及权限问题的。
/**
* 获取win磁盘信息
* @return win磁盘信息列表
*/
public static ArrayList<HashMap<String, String>> getWinHardDiskInfo() {
HashMap<String, String> hashMap = null;
ArrayList<HashMap<String, String>> diskList = new ArrayList<HashMap<String,String>>();
File[] roots = File.listRoots();
for (File file : roots) {
hashMap = new HashMap<String, String>();
hashMap.put("disk", file.getPath());
hashMap.put("total",Long.toString(file.getTotalSpace()));
hashMap.put("free", Long.toString(file.getFreeSpace()));
//hashMap.put("sn", getWinHardiskSn(file.getPath()));
diskList.add(hashMap);
}
return diskList;
}
在unix系统中可以执行
Runtime.getRuntime().exec("df");
df命令获取然后再java中解析字符信息可以获取到,这里不上code了。