My desktop application (written in Java) encrypts a file for an Android application.
A string portion from the entire file:
..." A kerékpár (vagy bicikli) egy emberi erővel hajtott kétkerekű jármű. 19. századi kifejlesztése "...
read from a file:
FileInputStream is = new FileInputStream("cycles.txt");
StringBuilder sb = new StringBuilder();
Charset inputCharset = Charset.forName("ISO-8859-1");
BufferedReader br = new BufferedReader(new InputStreamReader(is, inputCharset));
String read;
while((read=br.readLine()) != null) {
sb.append(read);
}
After reading the entire file, I encrypt it:
String text = sb.toString();
Encrypter er = new Encrypter();
byte[] bEncrypt = er.encrypt(text);
After the encryption I encode it to base64:
bEncrypt = Base64.getEncoder().encode(bEncrypt);
text = new String(bEncrypt, "ISO-8859-1");
After this, the file is saved on my PC's disk:
File file = new File(System.getProperty("user.dir") + "/files/encr_cycles.txt");
try {
PrintWriter pr = new PrintWriter(new FileWriter(file));
pr.print(text);
pr.close();
} catch (IOException e) {
e.printStackTrace();
}
From the Android application I read the file:
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("files/encr_cycles.txt"), "ISO-8859-1"));
// Read line by line
String mLine;
StringBuilder sb = new StringBuilder();
while ((mLine = reader.readLine()) != null) {
sb.append(mLine);
}
Decode and decrypt:
byte[] dec = Base64.decode(encryptedText, Base64.DEFAULT);
byte[] data= new Decipher().doFinal(dec);
String text= new String(data, "ISO-8859-1");
And the given text is:
" A kerékpár (vagy bicikli) egy emberi er?vel hajtott kétkerek? járm?. 19. századi kifejlesztése "
Note the "?" in the string? Some of the characters aren't decoded correctly.
Q1: What did I do wrong?
Q2: Am I using a wrong charset?
I changed the charset to "UTF-8" all over the applications (desktop & mobile). The problem was with the root file. The file wasn't saved in "UTF-8".
What did I done in eclipse:
The other solution is to save your file automatically while editing:
Window > Preferences > General > Content Types, set UTF-8 as the default
encoding for all content types.
Window > Preferences > General > Workspace, set "Text file encoding" to "Other : UTF-8".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.