Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix(android): remove incorrect trailing newline in readFile when using encoding #1626

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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