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();
}
本文介绍了一个Java方法,用于执行CMD命令并返回执行结果。通过Runtime.getRuntime().exec()方法启动外部进程,使用InputStream读取进程输出,最后将结果转换为字符串返回。
1116

被折叠的 条评论
为什么被折叠?



