【发布时间】:2014-03-03 04:51:21
【问题描述】:
我在某些设备上下载文件时遇到了一些问题,我收到 OOM 错误。这是我用来下载大文件的代码:
/**
* The size of the chunks that an file is split when writing to server.<br />
* 1024 * 1024 -> 1mb
*/
private static final int CHUNK_SIZE = 1024 * 1024;
File output = new File(sdCardPath, fileName);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(output);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int offset = 0;
// compute the number of chunks of 1 mb for downloading the file
// by parts
int parts = tmpFileSize / CHUNK_SIZE;
ByteString readingfile = null;
long progressUpdate = 0;
for (int partsCounter = 0; partsCounter < parts + 1; partsCounter++) {
try {
readingfile = serviceApi
.readFile(
session,
filehandle, offset, CHUNK_SIZE);
byte[] bytesRead = readingfile.toByteArray();
int numberOfBytesReaded = bytesRead.length;
offset = offset + numberOfBytesReaded;
progress.publish(""
+ (int) ((progressUpdate * 100) / tmpFileSize));
progressUpdate += numberOfBytesReaded;
fileOutputStream.write(bytesRead, 0,
numberOfBytesReaded);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
if (null != fileOutputStream) {
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
如果我在这里做错了什么,有人可以告诉我吗?谢谢。
基于@Ari 答案的解决方案我已经更新了代码。现在它被优化为仅使用 1mb (我不知道这是否是将进程分成块的最佳方法,但现在似乎有所改进,并且不会产生 OOM)。我将尝试通过检测我可以使用多少堆内存来进一步优化它,但我不确定我能否实现这一点。直到这似乎是最好的选择。 再次感谢@Ari。
【问题讨论】:
-
你下载的图片?
-
它可以是任何类型的文件。
标签: android file out-of-memory large-files