【问题标题】:Android ByteArrayBuffer holds more bytes than capacityAndroid ByteArrayBuffer 保存的字节数多于容量
【发布时间】:2014-03-14 14:11:17
【问题描述】:

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

【问题讨论】:

标签: java android io urlconnection


【解决方案1】:

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

【讨论】:

  • 不应该读取 20MB 的文件,因为它可能保存在 RAM 内存中并且可能没有内存映射?但有趣的是不必担心以这种方式下载一半的内容。
  • 是的,Android 应用程序有时会占用大量内存
猜你喜欢
  • 2014-12-07
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多