如果您已经有String
,不需要立即对其进行编码和解码,该字符串已经是某人解码原始字节的结果。
对于字符串文字,某人是编译器,将您的源代码读取为原始字节,并以您指定的编码对其进行解码。如果您以 Windows-1252 编码物理保存源文件,并且编译器将其解码为 Windows-1252,则一切正常。如果没有,您需要通过声明编译器在编译源代码时使用的正确编码来解决此问题...
The line
String utf8 = new String(accentedE.getBytes("utf-8"), Charset.forName("UTF-8"));
绝对什么也不做。 (编码为 UTF-8,解码为 UTF-8 == 无操作)
The line
utf8 = new String(accentedE.getBytes(), Charset.forName("UTF-8"));
将字符串编码为 Windows-1252,然后将其解码为 UTF-8。结果只能在 Windows-1252 中解码(因为it is在 Windows-1252 中编码,废话),否则你会得到奇怪的结果。
The line
utf8 = new String(accentedE.getBytes("utf-8"));
将字符串编码为 UTF-8,然后将其解码为 Windows-1252。与之前的情况相同的原则适用。
The line
utf8 = new String(accentedE.getBytes());
绝对什么也不做。 (编码为 Windows-1252,解码为 Windows-1252 == 无操作)
与整数类比可能更容易理解:
int a = 555;
//The case of encoding as X and decoding right back as X
a = Integer.parseInt(String.valueOf(a), 10);
//a is still 555
int b = 555;
//The case of encoding as X and decoding right back as Y
b = Integer.parseInt(String.valueOf(b), 15);
//b is now 1205 I.E. strange result
这两个都是无用的,因为在执行任何代码之前我们已经有了我们需要的东西,整数555
.
有必要
将字符串编码为原始字节离开你的系统并且需要将原始字节解码为字符串进入你的系统。无需立即编码和解码体制内.