开发者

Buffer & Modify OutputStream

is there a way to buffer a OutputStream, modify it before it is returned? Here is my code snippet:

public ServletOutputStream getOutputStream() throws IOException {
    BufferedOutputStream buffer = new BufferedOutputStream(super.getOutputStream());
    // Modify the buffer contents, before it 开发者_StackOverflow中文版is returned
    return new DelegatingServletOutputStream(buffer);
}

Thanks.


@oliholz's answer gives is one approach in which you modify the data "as it goes through" a filter stream to its destination.

Another approach is to send the output to a ByteArrayOutputStream, extract the contents to a byte array, modify the bytes, and finally write them to your "real" output stream.

Or you could extend ByteArrayOutputStream and override its close() method to do things when the stream is closed ... if that is what you mean. Or you could override getBytes to modify the bytes before returning them. Or override the write method to modify the bytes as they are being written. There are many ways you could approach it, depending on precisely what your requirements are.


You can write your own FilterOutputStream:

This class is the superclass of all classes that filter output streams. These streams sit on top of an already existing output stream (the underlying output stream) which it uses as its basic sink of data, but possibly transforming the data along the way or providing additional functionality.

    BufferedOutputStream buffer = new BufferedOutputStream(super.getOutputStream());

    FilterOutputStream filter = new FilterOutputStream(buffer) {
        @Override
        public void write( int b ) throws IOException {
            // modify b
            out.write( b );
        }
    };

    return new DelegatingServletOutputStream(filter);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜