Will DataInputStream override bytes with sequential reads

As the title says, could DataInputStream.read() override previously read bytes if there are more bytes available than the size of buffer, if in the first read some bytes were missed ?

There are fixed size packets exchanged between peers, and it is possible that two packets are available at the Socket. Let's say that size of one packet is 500, and there are two packets of total size 1000 available at the socket. Additionally, let's say that read fetches 400 bytes out of available 1000.

  • Is it even possible that read() doesn't read all 500 bytes if they are available ?

  • What will happen when read is invoked again, is it possible that more than 100 bytes are read ?

It is not really clear to me what happens in that case given the javadoc:

The first byte read is stored into element b[0], the next one into b[1], and so on. The number of bytes read is, at most, equal to the length of b.

I would like to know if below block of code should be modified as shown in comment to read only one packet fully.

    while ((readBytes = stream.read(buffer)) != -1) {

        totalBytes += readBytes;

        if (totalBytes < buffer.length) { // must this be != instead of < ?

            continue;
        }

        // all bytes are available
        else {

            break;
        }
Jon Skeet
people
quotationmark

Each time you call read(byte[]), it will:

  • Block until at least one byte is read from the input, or the input is closed
  • Copy bytes from the input into the array, starting at index 0 of the array
  • Return when there are no more bytes available (typically, anyway - it could have some delay where it waits a while for more to become available)

There's no memory of previous read calls - it won't start writing into the array at the previous index. If you want that behaviour, you need to write it yourself:

byte[] buffer = new byte[500];
int totalRead = 0;
while (totalRead < buffer.length) {
    // Pass in an offset and length, so we can keep reading into the
    // next part of the array.
    int bytesRead = input.read(buffer, totalRead, buffer.length - totalRead);
    if (bytesRead == -1) {
        throw new EOFException(); // Or whatever... stream ended early
    }
    totalRead += bytesRead;
}

... or call readFully() which will basically do the same thing.

people

See more on this question at Stackoverflow