一、执行一些比较复杂的语句时无法执行,直接退出来
解决方法:在语句前面加 cmd /c
原因我也不知道,很奇妙,浪费那么多时间。
二、调用Runtime.getRuntime().exec(s)命令程序阻塞
作为一个小白,一开始碰到这个问题,慌的要死无法解决,去找老师检查进度,老师说我内存4g太小,得加内存条,重点是走大创流程报销,哈哈哈开心,赵老师真是一个体贴学生的好老师!!!
然而装了8g内存条,问题依然没有解决,老样子一丁点改善都没有,我才发现问题没有那么简单,不是内存条的事。
去百度淘了一波教程,终于找到了我的得问题出在哪里。。。有一个前辈说的好:
执行某些命令的时候,如果cmds里的命令在后台打印出许多内容的话,process的 inputstream和errorstream的缓冲区会被填满,这个时候如果你不吧内容读出来的话就会阻塞在那里,而执行的进程因为内容打印不出来也会阻塞在那里不动。所以这种情况最好是开两个单独的线程去分别读inputstream和errorstream的内容。
直接贴解决代码
执行命令的代码
Process p = Runtime.getRuntime().exec(commandStr);
StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), "ERROR");
errorGobbler.start();
StreamGobbler outGobbler = new StreamGobbler(p.getInputStream(), "STDOUT");
outGobbler.start();
StreamGobbler类
public class StreamGobbler extends Thread {
InputStream is;
String type;
OutputStream os;
StreamGobbler(InputStream is, String type) {
this(is, type, null);
}
StreamGobbler(InputStream is, String type, OutputStream redirect) {
this.is = is;
this.type = type;
this.os = redirect;
}
public void run() {
InputStreamReader isr = null;
BufferedReader br = null;
PrintWriter pw = null;
try {
if (os != null)
pw = new PrintWriter(os);
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
if (pw != null)
pw.println(line);
System.out.println(type + ">" + line);
}
if (pw != null)
pw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally{
//FileUtil.close(pw);
// pw.close();
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
isr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// FileUtil.close(br);
// FileUtil.close(isr);
}
}
}