如何使BufferedReader更可靠?

时间:2013-12-22 21:53:59

标签: python io bufferedinputstream

peek中有方便的io.BufferedReader功能。但

peek([n])
    Return 1 (or n if specified) bytes from a buffer without advancing
the position. Only a single read on the raw stream is done to satisfy
the call. The number of bytes returned may be less than requested since
at most all the buffer’s bytes from the current position to the end are
returned.

返回的字节太少了。

我应该在哪里获得可靠的多字节peek(不使用read并破坏其他代码逐字节地解析数据流并从中解释数据)?

1 个答案:

答案 0 :(得分:1)

这取决于可靠的含义。缓冲类是专门为了尽可能地防止I / O(因为这是缓冲区的整个点)而定制的,因此它们只能保证它最多 1读取缓冲区。返回的数据量完全取决于缓冲区中已有的数据量。

如果您需要确切数量的数据,则需要更改基础结构。特别是,您可能需要使用更大的缓冲区重新打开流。

如果这不是一个选项,您可以提供一个包装类,以便您可以拦截所需的读取,并将数据透明地提供给实际想要使用该数据的其他代码。