该readOject()
方法使用 BlockedInputStream 读取字节。如果您检查readObject
of ObjectInputStream
,它正在调用
readObject0(false).
private Object readObject0(boolean unshared) throws IOException {
boolean oldMode = bin.getBlockDataMode();
if (oldMode) {
int remain = bin.currentBlockRemaining();
if (remain > 0) {
throw new OptionalDataException(remain);
} else if (defaultDataEnd) {
/*
* Fix for 4360508: stream is currently at the end of a field
* value block written via default serialization; since there
* is no terminating TC_ENDBLOCKDATA tag, simulate
* end-of-custom-data behavior explicitly.
*/
throw new OptionalDataException(true);
}
bin.setBlockDataMode(false);
}
byte tc;
while ((tc = bin.peekByte()) == TC_RESET) {
bin.readByte();
handleReset();
}
从流中读取的内容是使用binbin.readByte().
来读取的。这个类最终使用的是 InputStream.read()。从 read 方法的描述中:BlockiedDataInputStream
PeekInputStream
/**
* Reads the next byte of data from the input stream. The value byte is
* returned as an <code>int</code> in the range <code>0</code> to
* <code>255</code>. If no byte is available because the end of the stream
* has been reached, the value <code>-1</code> is returned. This method
* blocks until input data is available, the end of the stream is detected,
* or an exception is thrown.
所以基本上它会逐个字节地读取,直到遇到 -1。所以正如 EJP 所提到的,它永远不会提前知道要读取多少字节。希望这将帮助您理解它。