Skip to content

Commit

Permalink
Fix(android): remove incorrect trailing newline in readFile when usin…
Browse files Browse the repository at this point in the history
…g encoding (#1626)

* Different implementation of readFileAsString that does not insert stray newlines
  • Loading branch information
Chris Lloyd authored and jcesarmobile committed Jun 12, 2019
1 parent bf8027c commit 2e2bc4d
Showing 1 changed file with 11 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import com.getcapacitor.PluginRequestCodes;
import org.json.JSONException;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
Expand All @@ -26,7 +25,6 @@
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
Expand Down Expand Up @@ -114,29 +112,23 @@ private InputStream getInputStream(String path, String directory) throws IOExcep
File androidDirectory = this.getDirectory(directory);

if (androidDirectory == null) {
return null;
throw new IOException("Directory not found");
}

return new FileInputStream(new File(androidDirectory, path));
}

private String readFileAsString(InputStream is, Charset charset) throws IOException {
final StringBuilder text = new StringBuilder();
private String readFileAsString(InputStream is, String encoding) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];
int length = 0;

BufferedReader br = new BufferedReader(
new InputStreamReader(
is,
charset
)
);
String line;
while ((length = is.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
};

while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
return text.toString();
return outputStream.toString(encoding);
}

private String readFileAsBase64EncodedData(InputStream is) throws IOException {
Expand Down Expand Up @@ -174,7 +166,7 @@ public void readFile(PluginCall call) {
InputStream is = getInputStream(file, directory);
String dataStr;
if (charset != null) {
dataStr = readFileAsString(is, charset);
dataStr = readFileAsString(is, charset.name());
} else {
dataStr = readFileAsBase64EncodedData(is);
}
Expand Down

0 comments on commit 2e2bc4d

Please sign in to comment.