Getting a String from an InputStream
suggest changeA 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);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents