缓冲器与修改输出流
有没有办法缓冲 OutputStream,在返回之前对其进行修改?这是我的代码片段:
public ServletOutputStream getOutputStream() throws IOException {
BufferedOutputStream buffer = new BufferedOutputStream(super.getOutputStream());
// Modify the buffer contents, before it is returned
return new DelegatingServletOutputStream(buffer);
}
谢谢。
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 is returned
return new DelegatingServletOutputStream(buffer);
}
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
@oliholz 的答案给出了一种方法,您可以在数据“通过”过滤器流到达其目的地时对其进行修改。
另一种方法是将输出发送到 ByteArrayOutputStream ,将内容提取到字节数组,修改字节,最后将它们写入“真实”输出流。
或者您可以扩展 ByteArrayOutputStream 并重写其 close() 方法以在流关闭时执行操作...如果这就是您的意思。或者您可以覆盖
getBytes
以在返回字节之前修改字节。或者重写write
方法来修改正在写入的字节。您可以采用多种方法来实现它,具体取决于您的要求。@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 itsclose()
method to do things when the stream is closed ... if that is what you mean. Or you could overridegetBytes
to modify the bytes before returning them. Or override thewrite
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.您可以编写自己的 FilterOutputStream:
该类是所有过滤输出流的类的超类。这些流位于现有的输出流(底层输出流)之上,它用作基本数据接收器,但可能会沿途转换数据或提供附加功能。
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.