我正在尝试读取文件并将其上传到1 MB块大小的服务器。它工作正常高达13 MB但在此之后它给了我OutOfMemory Exception。我已经检查了缓冲区,它总是1MB大小,但我不知道为什么它会变成异常。有一件事我预测以前的读取字节不会立即被系统释放,所以我试图找到一些方法来释放它但是没有任何方法可以使用byte []来释放。
ByteArrayOutputStream byteBuffer = null;
try {
byteBuffer = new ByteArrayOutputStream();
byte[] buffer = new byte[maxchunksize];
int len = 0;
int startpoint = 0;
while ((len = is.read(buffer)) != -1) {
Log.i("Upload Chunk",""+buffer.length);
byteBuffer.write(buffer, 0, len);
String uploadresponse = UploadChunk(fileHandle, buffer, startpoint, EmailID);
if(!uploadresponse.equals("Chunk Added"))
{
Log.e("Upload Chunk", "something went wrong. Aborting upload");
break;
}
startpoint += buffer.length;
}
任何人都可以帮我解决这个问题吗?我的文件最大大小为25MB。
这是我得到的例外。
06-26 22:49:22.329: E/AndroidRuntime(15645): java.lang.OutOfMemoryError
06-26 22:49:22.329: E/AndroidRuntime(15645): at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)
06-26 22:49:22.329: E/AndroidRuntime(15645): at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:201)
06-26 22:49:22.329: E/AndroidRuntime(15645): at com.desiengineer.backgroundtask.EvidenceUploadService.onHandleIntent(EvidenceUploadService.java:101)
06-26 22:49:22.329: E/AndroidRuntime(15645): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
06-26 22:49:22.329: E/AndroidRuntime(15645): at android.os.Handler.dispatchMessage(Handler.java:99)
06-26 22:49:22.329: E/AndroidRuntime(15645): at android.os.Looper.loop(Looper.java:137)
06-26 22:49:22.329: E/AndroidRuntime(15645): at android.os.HandlerThread.run(HandlerThread.java:60)
答案 0 :(得分:0)
您必须将代码更改为:
while ((len = is.read(buffer)) != -1) {
Log.i("Upload Chunk",""+buffer.length);
byteBuffer.write(buffer, 0, len);
String uploadresponse = UploadChunk(fileHandle, buffer, startpoint, EmailID);
if(!uploadresponse.equals("Chunk Added"))
{
Log.e("Upload Chunk", "something went wrong. Aborting upload");
break;
}
startpoint += buffer.length;
byteBuffer.reset();
}
如果没有byteBuffer.reset(),您的缓冲区仍在扩展并导致OutOfMemoryException。
答案 1 :(得分:0)
删除ByteArrayOutputStream
。你没有使用它,它是你记忆问题的根源。