How to make a java program to print both out.println() and err.println() statements?

后端 未结 3 1393
一整个雨季
一整个雨季 2020-12-06 11:09

I have written the java code below, which executes another java program named \"Newsworthy_RB\".

Newsworthy_RB.java contains both the System.out.printlln() and Syste

3条回答
  •  难免孤独
    2020-12-06 11:29

    You need to pipe the output of both streams in a separate threads. Example code from here:

    Process p = Runtime.getRuntime().exec(cmd.array());
    copyInThread(p.getInputStream(), System.out);
    copyInThread(p.getErrorStream(), System.err);
    p.waitFor();
    return p.exitValue();
    
    private void copyInThread(final InputStream in, final OutputStream out) {
        new Thread() {
            public void run() {
                try {
                    while (true) {
                        int x = in.read();
                        if (x < 0) {
                            return;
                        }
                        if (out != null) {
                            out.write(x);
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        } .start();
    }
    

提交回复
热议问题