我在UTF-8
中有一个字符串,我首先将其转换为ISO-8859_1
,然后将其转换回UTF-8
并从中获取ISO8859_1
个字节。结果应该再次为ISO-8859-1
,但它会给我UTF-8
个字节。为什么呢?
import java.io.UnsupportedEncodingException;
public class Test {
public static void main(String[] args) throws
UnsupportedEncodingException {
String s0 = "H\u00ebllo";
byte[] bytes = s0.getBytes("ISO8859_1");
byte[] bytes1=s0.getBytes("UTF-8");
printBytes(bytes, "bytes"); //72 -21 108 108 111 (ISO-8859-1)
printBytes(bytes1, "bytes1"); //72 -61 -85 108 108 111 (UTF-8)
byte[] bytes2=new String(s0.getBytes("UTF-8"), "ISO8859_1").getBytes("ISO8859_1");
printBytes(bytes2, "bytes2"); //72 -61 -85 108 108 111 (UTF-8)
}
private static void printBytes(byte[] array, String name) {
System.out.print(name+": ");
for(int i=0; i<array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}
答案 0 :(得分:1)
这没有任何意义:
new String(s0.getBytes("UTF-8"), "ISO8859_1")
您正在使用UTF-8
编码解释byte[]
ISO8859_1
。您应该使用UTF-8
编码解释UTF-8
个字节:
new String(s0.getBytes("UTF-8"), "UTF-8")
然后会打印出来:
bytes: 72 -21 108 108 111
bytes1: 72 -61 -85 108 108 111
bytes2: 72 -21 108 108 111
你也说:
我在
中有一个字符串UTF-8
String
没有明确定义的内部编码,它是一个实现细节。创建String
后,没有编码,您只需String
。但是,您可以使用特定编码从中获取byte[]
。