Skip to content

Commit

Permalink
Merge pull request #5 from OutSystems/fix/RMET-1283/write-out-of-memory
Browse files Browse the repository at this point in the history
RMET-1283 Write file in blocks for memory economy
  • Loading branch information
nflsilva authored Jan 10, 2022
2 parents b89cf84 + dff244d commit 8d85496
Showing 1 changed file with 26 additions and 17 deletions.
43 changes: 26 additions & 17 deletions src/android/LocalFilesystem.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)));
}
Expand All @@ -414,7 +423,7 @@ public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
throw realException;
}

return rawData.length;
return totalSize;
}

private boolean isPublicDirectory(String absolutePath) {
Expand Down

0 comments on commit 8d85496

Please sign in to comment.