java.lang.Process清空缓冲区问题,普通信息和错误信息都要能及时清除要怎么弄

方法1:如果有普通信息,就清普通信息,如果没有则判断和清理错误信息,都没有则判断是否已结束
问题:发现如果程序即有普通信息,又有错误信息,会一直清理普通信息,不管错误信息,错误信息多了有可能会导致缓冲区爆掉
while (true) {
if (scStdOut.hasNextLine()) {
System.out.println(scStdOut.nextLine()); // Standard Output Information
exitFlag = false;
}else if (scErrOut.hasNextLine()) {
System.err.println(scErrOut.nextLine()); // Error Information
exitFlag = false;
}
if(exitFlag){
try {
Thread.sleep(20); // Nothing to do, sleep a while...
p.exitValue(); // ThrowIllegalThreadStateException, if the subprocess represented by this Process object has not yet terminated.
break;
} catch (InterruptedException ex) {
ex.printStackTrace();
} catch (IllegalThreadStateException ex) {
// Process still alive
}
}
}

方法2:每次循环都会判断和清理普通信息和错误信息
问题:如果没错误信息,代码运行时会一直停在scErrOut.hasNextLine()里,如果不判断直接nextLine,也是同样的停止,直到进程结束,这样普通信息的缓冲一直没清理,有可能导致普通信息过多爆掉
while (true) {
if (scStdOut.hasNextLine()) {
System.out.println(scStdOut.nextLine()); // Standard Output Information
exitFlag = false;
}
if (scErrOut.hasNextLine()) {
System.err.println(scErrOut.nextLine()); // Error Information
exitFlag = false;
}
//下面代码同方法1一样,省略掉

}

自己解决了,过了这么就再来看,还没人回答。。汗 自己贴上来吧,希望别人能用得上

上网找,一般都是说,两边都要及时清缓冲区的话要用多线程处理,我这个不需要

/**
 * 阻塞(自动清理输出缓冲区)
 * @param p
 * @return
 * @throws IOException
 */
public static String waitFor(Process p) throws IOException{
    String str = null;
    InputStream is1 = p.getInputStream(); 
    InputStream is2 = p.getErrorStream();  
    BufferedReader br = new BufferedReader(new InputStreamReader(is1)); 
    while (true) {
        boolean exitFlag = true; 
        if (is1.available() > 0) {
            Character c = new Character( (char) is1.read());
            System.out.print(c); 
            exitFlag = false;
        }
        if (is2.available() > 0) {
            Character c = new Character( (char) is2.read());
            System.out.print(c); 
            exitFlag = false;
        }
        if(exitFlag){
            try {
                Thread.sleep(100); // Nothing to do, sleep a while...
                p.exitValue(); // ThrowIllegalThreadStateException, if the subprocess represented by this Process object has not yet terminated.
                break;
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            } catch (IllegalThreadStateException ex) {
                // Process still alive
            }
        }
    }
    br.close();
    is1.close();
    p.destroy();
    return str;
}