documentation对于 CharsetDecoder
说
A decoder should always be used by making the following sequence of method invocations, hereinafter referred to as a decoding operation:
Reset the decoder via the reset method, unless it has not been used before;
Invoke the decode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;
Invoke the decode method one final time, passing true for the endOfInput argument; and then
Invoke the flush method so that the decoder can flush any internal state to the output buffer.
看起来 #3 和 #4 正在做同样的事情:表明没有更多输入,因此解码器可以完成。
如果我两者都做,我不确定我的错误处理逻辑应该是什么样子。
这两个操作有什么区别,为什么两者都是必要的?
最佳答案
What is the difference between these two operations?
- #3 完成解码并处理格式错误的输入,并将解码器的内部状态设置为“结束”。
- #4 调用抽象方法
implFlush()
(默认行为不执行任何操作),如果解码器的内部状态已经“结束”,则将其设置为“刷新”,否则抛出异常(如果尚未) “结尾”。
and why are both necessary?
它们都是考虑所有可能的 CharsetDecoder 实现所必需的。具体来说,为具体子类提供解码、格式错误输入处理和刷新缓冲资源之间的明确分离。
If I do both, I'm not sure what my error-handling logic should look like.
API 设计为在 #3 未成功调用时在任何情况下都会在 #4 处失败。在先前的#2 失败之后调用#3 通常是没有意义的。因此,您的 CharsetDecoder 不需要任何本地错误处理逻辑(try..finally block );只需按照推荐的顺序依次调用这些方法即可。
关于java - 为什么要刷新 CharsetDecoder?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27776142/