Android ByteArrayBuffer包含的字节数多于容量

时间:2014-03-14 14:11:17

标签: java android io urlconnection

我在项目中找到了以下代码。它工作,可以读取超过20MB的大文件。根据代码的设置方式,它应该在5000字节后失败。它为什么有效? ByteArrayBuffer的文档没有表明这一点。我已经验证了读循环迭代每个文件的所有字节。

http://developer.android.com/reference/org/apache/http/util/ByteArrayBuffer.html

        URLConnection ucon = url.openConnection();
        ucon.setReadTimeout(10000); // enables throw SocketTimeoutException
        InputStream is = ucon.getInputStream();

        long expectedFileSize = ucon.getContentLength();
        Log.d("Downloader", "expected file size: " + expectedFileSize);

        BufferedInputStream bis = new BufferedInputStream(is);

        // Read bytes to the Buffer until there is nothing more to read(-1).
        // This code can read 20MB and bigger mp3-files, ... why?!?
        ByteArrayBuffer baf = new ByteArrayBuffer(5000);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.flush();
        fos.close();

1 个答案:

答案 0 :(得分:1)

5000只是一个初始容量。一旦达到极限,它就会自动调整大小