java執行cmd命令,返回命令執行結果。
/**
* 執行單條指令
* @param cmd 命令
* @return 執行結果
* @throws Exception
*/
public static String command(String cmd) throws Exception{
Process process = Runtime.getRuntime().exec(cmd);
process.waitFor();
InputStream in = process.getInputStream();
StringBuilder result = new StringBuilder();
byte[] data = new byte[1024];
while(in.read(data) != -1){
String encoding = System.getProperty("sun.jnu.encoding");
result.append(new String(data,encoding));
}
return result.toString();
}