Getting a String from an InputStream

suggest change

A String can be read from an InputStream by decoding the bytes that were actually read. InputStream.read(byte[]) may return before the array is full, so decoding the whole array includes unread zeros and drops a short count.

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public String readString(InputStream input) throws IOException {
    byte[] bytes = new byte[50]; // maximum number of bytes to take from the stream
    int offset = 0;
    while (offset < bytes.length) {
        int n = input.read(bytes, offset, bytes.length - offset);
        if (n < 0) {
            break; // end of stream
        }
        offset += n;
    }
    // Bytes past the array stay in the stream. The platform default charset is used here.
    return new String(bytes, 0, offset);
}

Pass a charset to choose the decoding. UTF-8 is available on every Java platform:

return new String(bytes, 0, offset, StandardCharsets.UTF_8);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents