我在项目中找到以下代码。它可以工作并且可以读取超过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();

最佳答案

5000只是初始容量。达到极限后会自动调整大小

关于java - Android ByteArrayBuffer容纳的字节数多于容量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22407411/

10-10 20:10