Wednesday, October 3, 2012

How to Capture StdOut/StdErr in Java

package test;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.io.StringWriter;

public class Main {
    public static interface Function {
        void execute();
    }
    
    public static String capture1(PrintStream ps, Function func)
        throws IOException {
        PipedOutputStream pos = new PipedOutputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(
            new PipedInputStream(pos)));
        StringWriter sw = new StringWriter();
        String output = null;
        try {
            PrintStream old = ps;
            System.setOut(new PrintStream(pos));

            func.execute();
            System.out.flush();

            pos.close();

            System.setOut(old);

            int charsRead;
            char[] cbuf = new char[4096];
            while ((charsRead = br.read(cbuf, 0, cbuf.length)) != -1) {
                sw.write(cbuf, 0, charsRead);
            }
            output = sw.toString();
        }
        finally {
            br.close();
            sw.close();
        }
        return output;
    }
    
    public static String capture2(PrintStream ps, Function func)
        throws IOException {
        String output = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            PrintStream old = System.out;
            System.setOut(new PrintStream(baos));

            func.execute();
            System.out.flush();

            System.setOut(old);

            output = baos.toString();
        }
        finally {
            baos.close();
        }
        return output;
    }
    
    public static void main(String[] args) throws Exception {
        String output = capture1(System.out, new Function() {
            @Override
            public void execute() {
                System.out.println("Hello World");
                System.out.println("Bye World");
            }
        });
        System.out.println(output);
        
        
        output = capture2(System.out, new Function() {
            @Override
            public void execute() {
                System.out.println("Hello World");
                System.out.println("Bye World");
            }
        });
        System.out.println(output);
    }
}

No comments:

Post a Comment