为什么BufferedReader.read(char [])似乎在read()没有时跳过字符?

时间:2015-12-01 18:38:18

标签: java json io

我正在尝试使用BufferedReader.read(char[])方法代替read()方法以提高效率,但我注意到它不是因为某些原因而读取所有字符而我并不完全确定我的代码出了什么问题。代码和输出如下:

仅供参考:response类型为HttpUrlConnection

//使用read(char[])

 StringBuilder jsonResponse = new StringBuilder();
        BufferedReader reader = null;
        //build the response
        try {
            reader = new BufferedReader(new InputStreamReader(response.getInputStream()));
            char[] chars = new char[2048];
            while ((reader.read(chars)) != -1) {
                jsonResponse.append(chars);
                chars = new char[2048];
            }

        } finally {
            if (reader != null) {
                reader.close();
            }
        }

输出(“unique_id”值没有结束引号)

        ...lots of json...
        "version": "2.4",
        "info_url": null,
        "active": true,
        "bindable": true,
        "unique_id": "8f4af9f9-0f29-4957-87a3-1039ce983ede
        "extra": "{\"listing\":{\"imageUrl\":null,\"blurb\":null},\"provider\":{\"name\":\"Core\"}}",

//使用read()

StringBuilder jsonResponse = new StringBuilder();
BufferedReader reader = null;
//build the response
try {
    reader = new BufferedReader(new InputStreamReader(response.getInputStream()));
    int car = -1;
    while ((car = reader.read()) != -1) {
        jsonResponse.append((char)car);
    }

} finally {
    if (reader != null) {
        reader.close();
    }
}

输出(“unique_id”的结尾引用值为“)

         ...lots of json...
        "version": "2.4",
        "info_url": null,
        "active": true,
        "bindable": true,
        "unique_id": "8f4af9f9-0f29-4957-87a3-1039ce983ede",
        "extra": "{\"listing\":{\"imageUrl\":null,\"blurb\":null},\"provider\":{\"name\":\"Core\"}}",

1 个答案:

答案 0 :(得分:1)

我能想到的只有这个

    reader = new BufferedReader(new InputStreamReader(response.getInputStream()));
    char[] chars = new char[2048];
    int charsRead = 0;
    while ((charsRead = reader.read(chars)) != -1) {
        jsonResponse.append(chars, 0, charsRead);
        //no need to clear char[]
    }