java程序中执行windows下cmd命令很简单,代码所示:

Runtime.getRuntime().exec(command);//command是命令内容,如”dir”

当然由于java的平台无关性,linux的命令也可照常执行.

下面代码的的作用是执行一条命令,返回结果的字符串形式:

/**
* @param command cmd命令
* @return 命令执行后的字符
*/
private String runCmd(String command){
Process p;
try {
p = Runtime.getRuntime().exec(command);
InputStream inStream = new BufferedInputStream(p.getInputStream());
StringBuffer buffer = new StringBuffer();
for (;;)
{
int c = inStream.read();
if (c == -1)
break;
buffer.append((char) c);
}
String outputText = new String(buffer.toString().getBytes(“ISO-8859-1″));
inStream.close();
return outputText.trim();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

本文地址:http://www.yaronspace.cn/blog/index.php/archives/256

来自yaronspace.cn  本文链接:http://yaronspace.cn/blog/archives/256