用java执行wget(Runtime.exec)下载大文件(227M)时,只下载了42M程序就block在那里了。原因是Process的outputStream和errorStream没有读出来,程序在等待缓冲区清空,导致开启的子进程block了。
所以,启动Process后,必须读取它的这两个InputStream,或者使用ProcessBuilder来将这两个Stream合并,然后读取OutputStream就可以了。
/**
* execute command and get the output of stdout.
* @param command the command to execute.
* @return a String that contains the stdout.
* @throws Exception TODO:
*/
public String executeGetOutput(String command) throws Exception{
Process p = Runtime.getRuntime().exec(command);
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
InputStream isStdout = p.getInputStream();
InputStream isStderr = p.getErrorStream();
while(true){
this.readStream(isStdout, output);
this.readStream(isStderr, error);
try{
p.exitValue();
break;
}
catch(IllegalThreadStateException ex){
}
}
this.readStream(isStdout, output);
return output.toString();
}
private void readStream(InputStream is, StringBuilder output) throws IOException{
if(is.available() > 0){
byte[] bytes = new byte[is.available()];
is.read(bytes);
output.append(new String(bytes));
}
}