Question

I'm having these lines of code:

final int packetLength = 64 //just some constant
InputStream in = socket.getInputStream();
byte[] packet = new byte[packetLength];
int read = in.read(packet, 0, packetLength)

if(read != packetLength) {
    //End of stream=
}

Can I be sure that if the read(byte[], int, int) does not return the same value as the length it should read, the stream has reached the end of stream?

Because the next read() call should return -1 shouldn't it?

Was it helpful?

Solution

No, you can't be sure of that. InputStream doesn't block until it's read all the data you've requested - it blocks until it's read some data. (The default implementation of InputStream will read until it's read everything it can, but there's no guarantee that subclass implementations will do so.)

You should read until the read call returns -1 - or if you just want to read exactly packetLength bytes:

byte[] packet = new byte[packetLength];
int offset = 0;
while (offset < packetLength) {
    int bytesRead = in.read(packet, offset, packetLength - offset);
    if (bytesRead == -1) { 
        // Incomplete packet - handle however you want to
    }
    offset += bytesRead;
}
// Hooray - read the complete packet.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top