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);
    }
}

1 comment:

  1. Can anyone suggest how to convert the .wav (audio file) to a text file and vice-versa in Java?
    I want to convert the audio file to a text file in java i.e first the audio file will be played and after it is played it will copy the lyrics into a text file, and vice versa, in java. But, I don't know from where I will start it, so, can anyone tell me how to do that?

    ReplyDelete