Skip to content

Commit b2620a1

Browse files
author
Ron Radtke
committed
Fixing a problem with UTF8 encoded files being read as a stream
1 parent 7bb60a1 commit b2620a1

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

android/src/main/java/com/ReactNativeBlobUtil/ReactNativeBlobUtilFS.java

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,7 @@
2121
import com.facebook.react.modules.core.DeviceEventManagerModule;
2222

2323
import java.io.*;
24-
import java.nio.ByteBuffer;
2524
import java.nio.charset.Charset;
26-
import java.nio.charset.CharsetEncoder;
2725
import java.security.MessageDigest;
2826
import java.util.ArrayList;
2927
import java.util.HashMap;
@@ -360,20 +358,25 @@ else if (resolved == null) {
360358
fs = new FileInputStream(new File(path));
361359
}
362360

363-
byte[] buffer = new byte[chunkSize];
364361
int cursor = 0;
365362
boolean error = false;
366363

367364
if (encoding.equalsIgnoreCase("utf8")) {
368-
CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
369-
while ((cursor = fs.read(buffer)) != -1) {
370-
encoder.encode(ByteBuffer.wrap(buffer).asCharBuffer());
371-
String chunk = new String(buffer, 0, cursor);
365+
InputStreamReader isr = new InputStreamReader(fs, Charset.forName("UTF-8"));
366+
BufferedReader reader = new BufferedReader(isr, chunkSize);
367+
char[] buffer = new char[chunkSize];
368+
// read chunks of the string
369+
while (reader.read(buffer, 0, chunkSize) != -1) {
370+
String chunk = new String(buffer);
372371
emitStreamEvent(streamId, "data", chunk);
373372
if (tick > 0)
374373
SystemClock.sleep(tick);
375374
}
375+
376+
reader.close();
377+
isr.close();
376378
} else if (encoding.equalsIgnoreCase("ascii")) {
379+
byte[] buffer = new byte[chunkSize];
377380
while ((cursor = fs.read(buffer)) != -1) {
378381
WritableArray chunk = Arguments.createArray();
379382
for (int i = 0; i < cursor; i++) {
@@ -384,6 +387,7 @@ else if (resolved == null) {
384387
SystemClock.sleep(tick);
385388
}
386389
} else if (encoding.equalsIgnoreCase("base64")) {
390+
byte[] buffer = new byte[chunkSize];
387391
while ((cursor = fs.read(buffer)) != -1) {
388392
if (cursor < chunkSize) {
389393
byte[] copy = new byte[cursor];
@@ -407,7 +411,7 @@ else if (resolved == null) {
407411
if (!error)
408412
emitStreamEvent(streamId, "end", "");
409413
fs.close();
410-
buffer = null;
414+
411415
} catch (FileNotFoundException err) {
412416
emitStreamEvent(
413417
streamId,
@@ -710,8 +714,8 @@ static void exists(String path, Callback callback) {
710714
/**
711715
* List content of folder
712716
*
713-
* @param path Target folder
714-
* @param callback JS context callback
717+
* @param path Target folder
718+
* @param promise JS context promise
715719
*/
716720
static void ls(String path, Promise promise) {
717721
try {

0 commit comments

Comments
 (0)