JAVA IO:使用BufferedReader读取流的问题

时间:2013-10-10 09:43:00

标签: java json httpclient bufferedreader

我正在尝试使用缓冲读取器读取JSON响应,如下所示。我正在使用Apache Commons Http客户端。响应来自单行JSON,没有字符大约1060000,大小约为1 MB。面临的问题只是流的一部分被读者读取而其他部分缺失。如何在不丢失任何数据的情况下阅读完整的JSON。这是与BufferedReader的'CharBufferSize'相关还是流中没有字符?

InputStream stream = method.getResponseBodyAsStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
    builder.append(line);
}

3 个答案:

答案 0 :(得分:0)

尝试使用json解析器。

    import org.codehaus.jackson.*;

    JsonFactory fac = new JsonFactory();
    JsonParser parser =  fac .createJsonParser(stream);

答案 1 :(得分:0)

如果您只想将整个流复制到StringBuilder,则应使用InputStreamReaderchar - 数组缓冲区。

InputStream stream = method.getResponseBodyAsStream();

InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
StringBuilder builder = new StringBuilder();

char[] buffer = new char[4096];
int read;
while ((read = reader.read(buffer)) != -1) {
    builder.append(buffer, 0, read);
}

答案 2 :(得分:0)

最后,我能够使用Apache Commons库中的 IOUtils 来解决。这是代码。

BoundedInputStream boundedInputStream= new BoundedInputStream(stream);
BufferedReader reader = new BufferedReader(new InputStreamReader(boundedInputStream,"UTF-8"));

StringBuilder builder= new StringBuilder();
StringBuilderWriter writer = new StringBuilderWriter(builder);

IOUtils.copy(reader, writer);

虽然已经有一段时间了,但对某些人来说可能会有所帮助。

以下是原始来源Most Robust way of reading a file or stream using Java (To prevent DoS attacks)