diff --git a/src/android/LocalFilesystem.java b/src/android/LocalFilesystem.java index 051f9949..e2d28059 100644 --- a/src/android/LocalFilesystem.java +++ b/src/android/LocalFilesystem.java @@ -18,6 +18,7 @@ Licensed to the Apache Software Foundation (ASF) under one */ package org.apache.cordova.file; +import static java.lang.Math.min; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; @@ -382,26 +383,34 @@ public long writeToFileAtURL(LocalFilesystemURL inputURL, String data, append = true; } - byte[] rawData; - if (isBinary) { - rawData = Base64.decode(data, Base64.DEFAULT); - } else { - rawData = data.getBytes(Charset.defaultCharset()); - } - ByteArrayInputStream in = new ByteArrayInputStream(rawData); + int totalSize = 0; try { - byte buff[] = new byte[rawData.length]; String absolutePath = filesystemPathForURL(inputURL); - FileOutputStream out = new FileOutputStream(absolutePath, append); - try { - in.read(buff, 0, buff.length); - out.write(buff, 0, rawData.length); - out.flush(); - } finally { - // Always close the output - out.close(); + //We are writting the file in 300KB blocks so we dont run out of memory. + try (FileOutputStream fileOut = new FileOutputStream(absolutePath, append)) { + byte[] byteBuffer; + int blockSize = 300 * 1024; + String block = ""; + int blockOffset = 0; + while (blockOffset < data.length()) { + + block = data.substring(blockOffset, min(blockOffset + blockSize, data.length())); + + if (isBinary) { + byteBuffer = Base64.decode(block, Base64.DEFAULT); + } else { + byteBuffer = block.getBytes(Charset.defaultCharset()); + } + + fileOut.write(byteBuffer); + fileOut.flush(); + + totalSize += byteBuffer.length; + blockOffset += blockSize; + } } + if (isPublicDirectory(absolutePath)) { broadcastNewFile(Uri.fromFile(new File(absolutePath))); } @@ -414,7 +423,7 @@ public long writeToFileAtURL(LocalFilesystemURL inputURL, String data, throw realException; } - return rawData.length; + return totalSize; } private boolean isPublicDirectory(String absolutePath) {