1. 程式人生 > >java Runtime.getRuntime().exec 呼叫系統指令碼/命令注意事項

java Runtime.getRuntime().exec 呼叫系統指令碼/命令注意事項

錯誤的方法:

//CPUID
private static final String cpuid="dmidecode -t processor | grep 'ID' | head -1";

Process p = Runtime.getRuntime().exec(cpuid);

原因:不會被再次解析,管道符失效

正確的辦法:

linux下:

String[] command = { "/bin/sh", "-c", cpuid };

Process ps = Runtime.getRuntime().exec(command );

windows下:

String[] command = { "cmd", "/c", cpuid

 };

Process ps = Runtime.getRuntime().exec(command );