Java InputStream 8192个字节

时间:2013-05-27 13:20:03

标签: java

你有一个读取超过8192个字符的输入流吗?当我试着在那之后读它的主干。

InputStream stream = responseEntity.getContent();
// Read response data into buffer
ArrayList<Character> buffer = new ArrayList<Character>();
InputStreamReader reader = new InputStreamReader(stream);
int count = 1;
char[] buffer2 = new char[8192];
int j = 0;
while (count >= 0) {
    count = reader.read(buffer2);
    for (int i = 0; i < count; i++) {
        char c = buffer2[i];
        buffer.add(c);
    }
    j++;
}
stream.close();
StringBuilder builder = new StringBuilder(buffer.size());
for (Character ch : buffer) {
    builder.append(ch);
}

1 个答案:

答案 0 :(得分:1)

read(char[] buffer)方法不保证填充所有缓冲区。这通常发生在所有类似InputStream的接口中。你必须将读取放在一个循环中,直到它返回-1,这意味着它已到达流的末尾。

但我建议您使用Apache Commons IO,就像这样:

char[] buffer = IOUtils.toCharArray( stream )