Rafał Pydyniak
Rafał Pydyniak

Reputation: 539

InputStream read doesnt return -1

Hey I'm trying to send a file with java sockets but I'm having problems with read function of InputStream class. I've got this code

 InputStream is = sock.getInputStream();
    fos = new FileOutputStream(FILE_TO_RECEIVED);
    bos = new BufferedOutputStream(fos);

    byte [] buffer = new byte[4096];
    int bytesRead;
    int totalLength = 0;

    while(-1 != (bytesRead = is.read(buffer))) {
        bos.write(buffer, 0, bytesRead);
        totalLength += bytesRead;
    }
    bos.close();
    fos.close();
    is.close();

But it stops at the very end. I've examined this with System.err.println and with debugging and it seems like is.read never gives -1 as it should when the buffer ends. So for example I've got a file which has 5000 bytes, first read() returns 4096, then 4 (the rest of the file) and then nothing which causes endless loop. What might be the problem?

I really appreciate any help you can provide because I've been stuck there for like two hours now.

Upvotes: 1

Views: 223

Answers (1)

user207421
user207421

Reputation: 310893

read never gives -1 as it should when the buffer ends

That's not correct. It shouldn't return -1 'when the buffer ends'. It will only return -1 when the stream ends, which won't occur until the peer closes the connection.

Upvotes: 4

Related Questions