ByteArrayOutputStream .toByteArray();例外

时间:2016-01-12 16:43:42

标签: android protocol-buffers httpurlconnection bytearrayoutputstream

当我试着制作方法.toByteArray();总是属于异常,但日志没有显示,可能是什么问题:

protected byte[] GetResponseBytes(HttpURLConnection conn)
{
    byte[] data2 = null;
    try
    {
        int nRead;
        byte[] data = new byte[16384];
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream buff = new ByteArrayOutputStream();

        while ((nRead = is.read(data, 0, data.length)) != -1)
            buff.write(data, 0, nRead);

        buff.flush();
        buff.close();
        is.close();
        data2 = buff.toByteArray();
        return data2;

    }
    catch (Exception ex)
    {
        Log.d(" ERROR ", "[ data loader - post response bytes ] "+ex.getMessage());
        return data2;
    }
}

我打电话给这样的方法:

byte[] data = GetResponseBytes(conn);
            element = parser.parseFrom(data);

解析器是一个protocolBuffer并且是一个例外

2 个答案:

答案 0 :(得分:0)

您已关闭该行的缓冲区“buff”: buff.close(); 然后你正在访问它。访问后关闭它 - 而不是之前: - )

答案 1 :(得分:0)

data2 = buff.toByteArray(); buff.flush(); buff.close();`