java中调用外部命令
public class execcommond{
public execcommond(){}
/**
* 执行一条命令
* @param execstr string 命令字符串
* @return string 执行命令错误时的信息。
*/
public static string exec(string execstr) {
runtime runtime = runtime.getruntime(); 取得当前运行期对象
string outinfo=””; //执行错误的输出信息
try {
string[] args = new string[] {“sh”, “-c”, execstr};//执行linux下的命令
//执行windows下的命令
// string[] args = new string[] {“cmd”, “-c”, execstr};
process proc = runtime.exec(args); //启动另一个进程来执行命令
inputstream in = proc.geterrorstream();//得到错误信息输出。
bufferedreader br = new bufferedreader(new inputstreamreader(in));
string line = “”;
while ( (line = br.readline())
!= null) {
outinfo = outinfo + line + “\n”;
system.out.println(outinfo);
}
// 检查命令是否失败。
try {
if (proc.waitfor() != 0) {
system.err.println(“exit value = ” +
proc.exitvalue());
}
}
catch (interruptedexception e) {
system.err.print(e);
e.printstacktrace();
}
}
catch (ioexception e) {
flag = false;
system.out.println(“exec error: ” + e.getmessage());
e.printstacktrace();
}
finally {
return outinfo;
}
}
}