FileChannel.transferFrom(source,0,source.size())在尝试复制大小约为2GB的文件时,会出现以下OutOfMemory异常。由于文件较大,我理解内存问题。我们可以通过循环处理小块文件来解决它吗?
01-22 17:27:03.365: W/System.err(28538): java.io.IOException: mmap failed: ENOMEM (Out of memory)
01-22 17:27:03.375: W/System.err(28538): at java.nio.MemoryBlock.mmap(MemoryBlock.java:119)
01-22 17:27:03.375: W/System.err(28538): at java.nio.FileChannelImpl.map(FileChannelImpl.java:249)
01-22 17:27:03.380: W/System.err(28538): at java.nio.FileChannelImpl.transferFrom(FileChannelImpl.java:381)
01-22 17:27:03.380: W/System.err(28538): at com.druva.inSync.util.InSyncIOUtils.copyFile(InSyncIOUtils.java:123)
01-22 17:27:03.380: W/System.err(28538): at com.druva.inSync.AsyncTasks.ProcessUploadTask.getFileItemForFile(ProcessUploadTask.java:102)
01-22 17:27:03.380: W/System.err(28538): at com.druva.inSync.AsyncTasks.ProcessUploadTask.processUploads(ProcessUploadTask.java:124)
01-22 17:27:03.380: W/System.err(28538): at com.druva.inSync.AsyncTasks.ProcessUploadTask.doInBackground(ProcessUploadTask.java:53)
01-22 17:27:03.380: W/System.err(28538): at com.druva.inSync.AsyncTasks.ProcessUploadTask.doInBackground(ProcessUploadTask.java:1)
01-22 17:27:03.380: W/System.err(28538): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-22 17:27:03.380: W/System.err(28538): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-22 17:27:03.380: W/System.err(28538): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-22 17:27:03.380: W/System.err(28538): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-22 17:27:03.380: W/System.err(28538): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-22 17:27:03.380: W/System.err(28538): at java.lang.Thread.run(Thread.java:841)
01-22 17:27:03.385: W/System.err(28538): Caused by: libcore.io.ErrnoException: mmap failed: ENOMEM (Out of memory)
修改
我尝试了以下代码:
for (long n = 0, s = source.size() >> 1; n < s;) {
Log.d("copy file", "inside for loop " + destination.size());
long c = destination.transferFrom(source, n, s - n);
n += c;
Log.d("copy file", "results: c=" + c + ", n=" + n);
}
但它只复制文件的前半部分......
答案 0 :(得分:4)
我遇到了与FileChannel.transferFrom相同的问题,但我偶尔也会看到文件小于512MB的ENOMEM错误。
这里是我最终用于以较小的块传输文件的代码:
// Transfer file in 256MB blocks
final long blockSize = Math.min(268435456, sourceChannel.size());
long position = 0;
while (destinationChannel.transferFrom(sourceChannel, position, blockSize) > 0) {
position += blockSize;
}
transferFrom方法返回复制成功的字节数。如果它返回大于零的数字,则复制整个块,因此尝试复制另一个块。当它没有复制任何东西时,你就完成了。