Java ProcessBuilder:转发已启动进程的stdout和stderr,而不会阻塞主线程

Java ProcessBuilder:转发已启动进程的stdout和stderr,而不会阻塞主线程,第1张

Java ProcessBuilder:转发已启动进程的stdout和stderr,而不会阻塞主线

在Java 6或更早版本中,唯一的办法是使用所谓的

StreamGobbler
(开始创建):

StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), "ERROR");// any output?StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(), "OUTPUT");// start gobblersoutputGobbler.start();errorGobbler.start();

private class StreamGobbler extends Thread {    InputStream is;    String type;    private StreamGobbler(InputStream is, String type) {        this.is = is;        this.type = type;    }    @Override    public void run() {        try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null)     System.out.println(type + "> " + line);        }        catch (IOException ioe) { ioe.printStackTrace();        }    }}

对于Java 7,请参阅Evgeniy Dorofeev的答案。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5146062.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-18

发表评论

登录后才能评论

评论列表(0条)

保存