【发布时间】: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();
【问题讨论】:
-
hc.apache.org/httpcomponents-core-4.2.x/httpcore/apidocs/org/… - "public void append(int b) 将 b 字节追加到此缓冲区。如有必要,缓冲区的容量会增加,以容纳额外的字节。"
-
我认为这是官方文档(它缺少此信息)... developer.android.com/reference/org/apache/http/util/… 谢谢。 PS:我从代码中得到了第一个OutOfMemory。
标签: java android io urlconnection