响应输出流内容长度?
我正在通过各种方法写入输出流。在关闭它之前,如何找出输出流的内容长度?
I am writing to output stream through various methods. How can I, before I close it, find out content length of the outputstream?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最简单的方法可能是将其包装在另一个
OutputStream
实现中,该实现转发所有写入请求,但保留一个内部计数器。然后你只需写信即可。实施起来应该不会太难——事实上可能已经有一个了。编辑:只是猜测一个合理的名称(
CountingOutputStream
)在 Apache Commons 中提出了一个实现IO。编辑:如其他地方所述,如果这是针对 HTTP 并且您的客户端尚未缓冲完整数据(在这种情况下,我认为它可以计算出内容长度),那么您由于需要在写入数据之前写入长度,可能会出现问题。在某些情况下,您可能会发现它会工作到一定大小(客户端缓冲),然后失败。在这种情况下,大卫的解决方案将是合适的。
The easiest way is probably to wrap it in another
OutputStream
implementation which forwards on all the write requests, but keeps an internal counter. Then you just write to that instead. Shouldn't be too hard to implement - and indeed there may be one already.EDIT: Just guessing at a sensible name (
CountingOutputStream
) came up with an implementation in Apache Commons IO.EDIT: As noted elsewhere, if this is for HTTP and your client isn't already doing buffering of the full data (in which case I'd have thought it could work out the content length), you may have problems due to needing to write the length before writing the data. In some cases you may find that it will work up to a certain size (which the client buffers) and then fail. In that case, David's solutions will be appropriate.
问题是您必须在开始将任何数据写入输出流之前在响应标头中设置内容长度。因此,您的选择是:
The problem is that you must set the content length in the response header before you start writing any data to the output stream. So your options are:
您可以考虑写入自己的 ByteArrayOutputStream 并在最后将其刷新到响应输出流。
You may consider writing to your own ByteArrayOutputStream and flush it to the response output stream at the very end.