From cd4e023656c327815f9059490d3db9c345f85eee Mon Sep 17 00:00:00 2001 From: Maurus Cuelenaere Date: Tue, 3 Sep 2019 18:44:06 +0200 Subject: [PATCH] RNFetchBlobFS.writeFile(): ensure that files are closed properly in all cases and that stringToBytes() (which could potentially OOM) is called *before* the output file is opened --- .../java/com/RNFetchBlob/RNFetchBlobFS.java | 46 +++++++++++++------ 1 file changed, 31 insertions(+), 15 deletions(-) diff --git a/android/src/main/java/com/RNFetchBlob/RNFetchBlobFS.java b/android/src/main/java/com/RNFetchBlob/RNFetchBlobFS.java index 101e8033a..aa145ff36 100644 --- a/android/src/main/java/com/RNFetchBlob/RNFetchBlobFS.java +++ b/android/src/main/java/com/RNFetchBlob/RNFetchBlobFS.java @@ -69,32 +69,45 @@ static void writeFile(String path, String encoding, String data, final boolean a } } - FileOutputStream fout = new FileOutputStream(f, append); // write data from a file if(encoding.equalsIgnoreCase(RNFetchBlobConst.DATA_ENCODE_URI)) { String normalizedData = normalizePath(data); File src = new File(normalizedData); if (!src.exists()) { promise.reject("ENOENT", "No such file '" + path + "' " + "('" + normalizedData + "')"); - fout.close(); return; } - FileInputStream fin = new FileInputStream(src); byte[] buffer = new byte [10240]; int read; written = 0; - while((read = fin.read(buffer)) > 0) { - fout.write(buffer, 0, read); - written += read; + FileInputStream fin = null; + FileOutputStream fout = null; + try { + fin = new FileInputStream(src); + fout = new FileOutputStream(f, append); + while ((read = fin.read(buffer)) > 0) { + fout.write(buffer, 0, read); + written += read; + } + } finally { + if (fin != null) { + fin.close(); + } + if (fout != null) { + fout.close(); + } } - fin.close(); } else { byte[] bytes = stringToBytes(data, encoding); - fout.write(bytes); - written = bytes.length; + FileOutputStream fout = new FileOutputStream(f, append); + try { + fout.write(bytes); + written = bytes.length; + } finally { + fout.close(); + } } - fout.close(); promise.resolve(written); } catch (FileNotFoundException e) { // According to https://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html @@ -129,12 +142,15 @@ static void writeFile(String path, ReadableArray data, final boolean append, fin } FileOutputStream os = new FileOutputStream(f, append); - byte[] bytes = new byte[data.size()]; - for(int i=0;i