简体   繁体   English

Android-写入/读取文件编码

[英]Android - Encoding on write/read file

I have a String which contains 2 byte (16 bit) ASCII characters from encryption. 我有一个包含2个字节(16位)ASCII字符的字符串,来自加密。 Then I write it to a file with this code: 然后,使用以下代码将其写入文件:

String result = encrypt("text"); //some encryption method
FileOutputStream fos = new FileOutputStream(filename);
fos.write(result.getBytes("ISO-8859-15"));
fos.flush();
fos.close();

The problem is when I read the file, the string value is already different. 问题是当我读取文件时,字符串值已经不​​同。 Below is the code which I use to read the file: 下面是我用来读取文件的代码:

InputStream inputStream = new FileInputStream(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "ISO-8859-15"));
String line;
String txt = "";
while ((line = br.readLine()) != null) txt = txt + line;

I found that String txt is already different than String result. 我发现String txt已经与String结果不同。 I even made a method to sum all the character's ASCII in the string, and found it different. 我什至提出了一种将字符串中所有字符的ASCII求和的方法,发现它与众不同。 And I have no idea what's my mistake. 而且我不知道我的错误是什么。 Please help. 请帮忙。

If you've encrypted it, you don't want to write it out as a string and apply an encoding. 如果已加密,则不想将其作为字符串写出并应用编码。 Every encryption method I know of treats data as an array of bytes. 我所知道的每种加密方法都将数据视为字节数组。 You need to do any character set converting before encryption, and after decryption. 您需要在加密之前和解密之后进行任何字符集转换。 In Java you shouldn't even be holding the post-encryption data as a string, it ought to be an array of bytes. 在Java中,您甚至不应该将加密后的数据保存为字符串,它应该是字节数组。

Also, there is no such thing as 16 bit ASCII. 而且,没有16位ASCII这样的东西。 ASCII is 8 bit. ASCII是8位。 You're using some sort of wide character data or 16 bit unicode, not ascii. 您正在使用某种宽字符数据或16位unicode,而不是ascii。 http://en.wikipedia.org/wiki/ASCII http://en.wikipedia.org/wiki/ASCII

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM