1

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?

1 Answer 1

3

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.
Sign up to request clarification or add additional context in comments.

5 Comments

So let in in the example above be a SocketInputStream, I should call read(byte[], int, int) again and again and always append the data to a buffer until the read method finally returns -1 or packetLength bytes were read?
@MinecraftShamrock: If you're only interested in reading packetLength bytes, that's fine. If you want to read to the end of the stream, you need to keep reading until read returns -1.
I want to read packetLength bytes. But until now I handled it as end of stream if the bytes read were fewer than packetLength. So I don't want to read to the end of stream but I need to know if the end of stream has been reached.
@MinecraftShamrock: Right, I'll edit my answer then.
Thank you so much! That seems to be the solution for a really nasty problem I had.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.