我正在尝试制作一个Java程序,通过cmd或终端获取硬盘序列号。我在Windows和Linux操作系统上都进行了尝试。但是在Linux上我遇到了问题,当我在终端中键入hdparm -I /dev/sda | grep Serial
时,它会返回一个空格,而不是显示硬盘序列号。
我的问题是,如何获取或显示硬盘序列号。
以下是我的代码:
private static String OS= System.getProperty("os.name").toLowerCase();
private static String system;
private static String serial;
private void getVol(String drive)
{
String query=new String();
if(isWindows())
{
query="cmd /c"+" vol "+drive+":";
}
else if(isUnix())
{
query="hdparm -I /dev/sda | grep Serial";
}
try
{
Runtime rt=Runtime.getRuntime();
InputStream is=rt.exec(query).getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
String line;
if(isWindows())
{
br.readLine();
line=br.readLine();
line=line.substring(line.lastIndexOf(" ")+1);
serial=line;
}
else if(isUnix())
{
line=br.readLine();
serial=line;
}
}catch(IOException ex)
{
ex.printStackTrace();
}
}
private static boolean isWindows() {
return (OS.indexOf("win") >= 0);
}
private static boolean isUnix()
{
return (OS.indexOf("nux") >= 0);
}
public static void main(String args[])
{
MainClass f=new MainClass();
f.getVol("C");
System.out.println(serial);
}
String yourShellCommand = "/sbin/hdparm -I /dev/sda | grep Serial"; String[] commandAndArgs = new String[]{ "/bin/sh", "-c", yourShellCommand }; Runtime.getRuntime().exec(commandAndArgs);
- giusc