有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android ByteArrayBuffer的字节数大于容量

我在一个项目中发现了以下代码。它工作正常,可以读取超过20MB的大文件。根据代码的设置方式,5000字节后应该会失败。它为什么有效?ByteArrayBuffer的文档中没有这样的内容。我已经验证了读取循环对每个文件的所有字节进行迭代

http://developer.安卓.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) 个答案

  1. # 1 楼答案

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