package cn.ahstu;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class RunCmd {
private String ErrorMessage="";
private String ExecuteMessage="";
public String getErrorMessage() {
return ErrorMessage;
}
public void setErrorMessage(String errorMessage) {
ErrorMessage = errorMessage;
}
public String getExecuteMessage() {
return ExecuteMessage;
}
public void setExecuteMessage(String executeMessage) {
ExecuteMessage = executeMessage;
}
//执行可执行文件
public String RunCMD(String strcmd) {
String str = "";
Runtime run=null;
Process p=null;
try {
run = Runtime.getRuntime();// 返回与当前 Java 应用程序相关的运行时对象
p = run.exec(strcmd);// 启动另一个进程来执行命令
BufferedInputStream in = new BufferedInputStream(p.getInputStream());
BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
BufferedInputStream inErr = new BufferedInputStream(p.getErrorStream());
BufferedReader inBrErr = new BufferedReader(new InputStreamReader(inErr));
String lineStr=null;
ErrorMessage="";
while ((lineStr = inBrErr.readLine()) != null)
// 获得命令执行后在控制台的输出信息
ErrorMessage += lineStr;
if(ErrorMessage!=null && ErrorMessage.length()>0)
System.out.println("错误信息:"+ErrorMessage);// 打印输出信息
lineStr=null;
ExecuteMessage="";
while ((lineStr = inBr.readLine()) != null)
// 获得命令执行后在控制台的输出信息
ExecuteMessage += lineStr;
if(ExecuteMessage!=null && ExecuteMessage.length()>0)
System.out.println("输出信息:"+ExecuteMessage);// 打印输出信息
// 检查命令是否执行失败。
if (p.waitFor() != 0) {
if (p.exitValue() == 1) // p.exitValue()==0表示正常结束,1:非正常结束
{
System.err.println("命令"+strcmd+"执行失败!"+p.waitFor()+"*"+p.exitValue());
str += "Error";
}
}
inBr.close();
in.close();
} catch (Exception e) {
System.out.println("执行命令出错:"+strcmd);
//e.printStackTrace();
}
finally{
p.destroy();
p=null;
}
return ExecuteMessage;
}
public static void main(String argv[]){
RunCmd runCmd=new RunCmd();
String string=runCmd.RunCMD("ping www.csdn.net");
System.out.println(string);
}
}