1

I have the following code to read an input stream from a socket connection:

private ByteBuffer toByteBuffer(BufferedInputStream is) throws IOException {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int l;
    byte[] data = new byte[256];
    while ((l = is.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, l);
    }
    buffer.flush();
    return ByteBuffer.wrap(buffer.toByteArray());
}

In the first iteration of the while loop, everything goes fine and I am able to get the data into the buffer. But then it gets stuck at while ((l = is.read(data, 0, data.length)) != -1) {

I think (and I might be wrong) it is because it is waiting for more data from the socket, which is never going to come.

How do I handle this situation/hang?

1 Answer 1

4

As the BufferedInputStream method you are using does not block you get the situation that as soon as your InputStream does not have any data and is not closed you don't get a -1 but a 0. This will send your method into an endless loop.

So for reading local streams it is better to check for read() <= 0 as you usually get the data fast enough.
The best way is to make sure there is an eof by closing the stream.

Sign up to request clarification or add additional context in comments.

Comments

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.