Currently I am trying to read a not so short stream from a response of content length 37743. I am using the read(char[] buffer, int offset, int length), yet not all the stream is being read when comparing it to the original json file I am reading. I’ve tried to check if this is a common issue but I cannot find any reasons why this can be the problem:
- max length of the String builder?
- max length of the char[] ?
- buffer length ? (currently 8192)
- incorrect while condition ? (following snippet)
while ((reader.read(buffer, 0, buffer.length)) != -1)
sb.append(String.valueOf(buffer)); //sb is the String builder
Note when the buffer length is changed, the result changes again, e.g. when changed to 1024, the same result obtained with the 8192 buffer was achieved plus another piece of text which is not consistent with the original json string.
You should never ignore the result of
Reader.read(). It returns -1 if the end of the stream is reached. If not, it returns the number of chars that have been read. Assuming that it reads exactly the number of chars you asked it to read is wrong.Change it to