I am trying to understand this snippet of code
DataInputStream stream =
new DataInputStream(
new ByteArrayInputStream(messageBuffer));
int messageLength = stream.readInt();
char recordType = (char) stream.readByte();
byte padding = stream.readByte();
short numberRecords = stream.readShort();
messageBuffer is initialised as new byte[32768] as is populated via a Socket.read() method. What i dont understand is once messageLength has been initialised to stream.readInt(), how will the second second statement work i.e. recordType?
Wouldnt the first statement read an int from the beginning of the byte array and the next statement read a byte from the beginning of the byte array? How exactly does it know from which point to read the bytes, ints, shorts etc?
From the documentation:
A
ByteArrayInputStream
contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by theread
method.
In other words, DataInputStream
simply reads from the ByteArrayInputStream
, while the latter remembers the current position in the byte array and advances it every time some data has been read.