最近在公司实习,遇到一个让人头疼的bug,(debug的时候当执行在readLine()时,就卡死了,不能执行了,但是javaw也没有“死掉”)上网查遍解决方案,有的读不明白,有的没有从根本上解决问题,后来求助同事,瞬间就给解决了,这个bug值得记录下来,以后一定还会遇到的!
使用java来执行cmd命令
pulic static void executeCommand(String command)throws Exception{
Process ps = null;
InputStreamReader input = null;
BufferedReader errorBuf = null;
if("".equals(command)){
抛出一个异常。。。。。
}
try{
ps = Runtime.getRuntime().exec(command);
InputStream inputStream = null;
BufferedReader inputReader = null;
inputStream = new InputStreamReader(ps.getInputStream());
inputReader = new BufferedReader(inputStream);
System.out.println(inputReader.toStream());
StringBuilder inputBuf = new StringBuilder();
String inputLine = null;
while((inputLine=inputReader.readLine()) != null){
inputBuf = append(inputLine);
}
input = new InputStreamReader(ps.getErrorStream());
errorBuf = new BufferedReader(input);
System.out.println(errorBuf.toString());
StringBuilder buf = new StringBuilder();
String line = null;
while((line=errorBuf.readLine()) != null){
buf.append(line);
}
//等待命令执行结束,获取执行结果
ps.waitFor();
String errorStr = buf.toString();
if (errorStr != null && !errorStr.equals("")) {
if ("lalala_1004".equals(errorStr)) {
throw new DoorsInternalException(errorStr);
}else if ("lalala_1005".equals(errorStr)) {
throw new AuthenticationException(errorStr);
}.......其他异常
finally {
if(errorBuf != null){
try {
errorBuf.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
if(input != null){
try {
input.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
if (ps != null) {
ps.destroy();
}
}
}
}