DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

DebugInputStream

04.09.2005
| 6006 views |
  • submit to reddit
        This class is useful for printing the data coming through an InputStream without copying that data into memory first.

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class DebugInputStream extends FilterInputStream {

    private OutputStream debugOut;

    public DebugInputStream(InputStream in, OutputStream debugOut) {
        super(in);
        this.debugOut = debugOut;
    }

    public int read() throws IOException {
        int c = super.read();
        debugOut.write((char) c);
        return c;
    }

    public int read(byte[] b) throws IOException {
        int readCount = super.read(b);
        for (int i = 0; i < readCount; i++) {
            debugOut.write((char) b[i]);
        }
        return readCount;
    }

    public int read(byte[] b, int offset, int length) throws IOException {
        int readCount = super.read(b, offset, length);
        int readTo = offset + readCount;
        for (int i = offset; i < readTo; i++) {
            debugOut.write((char) b[i]);
        }
        return readCount;
    }

}
    

Comments

Snippets Manager replied on Wed, 2007/02/14 - 2:44pm

Surely a more reasonable way of doing this is to just wrap the input stream in a buffered reader and print it to a PrintStream? You'll be buffering lines into memory, but these aren't likely to be that long (and if you don't want to do that I suppose you can read it on a per character basis without the buffered reader, but that's likely to lose out on speed).