最近在使用JAVA调用Runtime.getRuntime()执行数据库备份命令时,发现一直不成功,调试时总是阻塞在读取输出的地方,代码如下:
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command, null, new File(mebInstallPath));
BufferedReader buffer = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = null;
while ((line = buffer.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code " + exitVal);
执行到while循环的地方就阻塞了,百思不得其解,最后看到了haozhugogo发的帖子(https://blog.csdn.net/haozhugogo/article/details/78363930)之后,才意识到问题所在。问题确实如他所说,因为我执行的备份命令产生的标准输出比较多,而标准输出缓冲区不够大,由于缓冲区的问题,由于java进程没有清空写到缓冲区的内容,结果导致程序一直在等待。
最后修改后,程序运行正常
InputStream is2 = null;
BufferedReader br2 = null;
try
{
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command, null, new File(mebInstallPath));
final InputStream is1 = pr.getInputStream();
new Thread(new Runnable() {
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(is1));
try {
while (br.readLine() != null)
;
} catch (Exception e) {
e.printStackTrace();
}
finally
{
try {
br.close();
is1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start(); // 启动单独的线程来清空p.getInputStream()的缓冲区
is2 = pr.getErrorStream();
br2 = new BufferedReader(new InputStreamReader(is2));
String line = null;
while ((line = br2.readLine()) != null)
System.out.println(line);
int exitVal = pr.waitFor();
System.out.println("Exited with error code " + exitVal);
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
finally
{
try {
br2.close();
is2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
在此感谢haozhugogo,本文也作为自己的备忘吧