使用 Writer 时设置 contet-length?

Setting contet-length when using Writer?

我正在研究一些响应包装器。当使用 OutputStream 时,我可以确定字节数。但是,当使用 Writer 时,我将内容缓冲为 char[],稍后用于写入输出。

这是一个有点菜鸟的问题,但是如何在使用 char[] 时确定真实的 content-length(我想设置 header - 我知道我没有到,但我想要)?我的意思是,我可以使用使用过的编码将字符转换为字节,然后刷新字节,但我想跳过另一次转换。

还有其他想法吗?

这取决于您使用的字符编码:

  • 如果您使用的是 8 位编码(例如 Latin-1),并且只有可映射的字符要转换,则字符数与字节数相同。

  • 否则,技术上可以计算出字符流将编码为1的字节数,但没有一个简单的[=23] =]和高效的方法。


Yeah, but that is a point, that I do not know the encoding in front and user may use anything. I don't see any other pragmatical way of doing this besides converting to byte[] - which probably happens under the hood, i guess.

其实应该很容易分辨编码是什么。在响应包装器上调用 getCharacterEncoding()。如果您在调用 getWriter 之后执行此操作,那么它将是用于创建编写器的编码。 (至少,javadocs 是这么暗示的...)


1 - 例如,对于 UTF-8,您将首先实现 char 值到 Unicode 代码点的映射,然后算出对每个代码点进行编码需要多少字节.这可以在不复制等的情况下完成,但是您需要从头开始对其进行编码……除非您可以找到执行此操作的第 3 方库。