面试之Java String 编码相关
另有一篇我的字符编码本质入门的文章见这里:https://www.cnblogs.com/uncleguo/p/16008551.html
实话说,作为一个多年Java老年程序员,直到近来,在没有决心花时间搞清楚Java String的编码相关问题之前, 自己也都还是似懂非懂,一脸懵逼的。设想如果在面试中,有同学能够条理清晰的回答下面的问题,那必是非常了得之人,论智慧武功应该均在本人之上:-)。
问:请预测下面程序的输出,并解释原因。printHexBinary方法为16进制打印Byte
1 String str = "中"; 2 3 byte[] bufferGBK = str.getBytes("GBK"); 4 System.out.println("bufferGBK = "+printHexBinary(bufferGBK)) ; 5 6 String gbkString =new String(bufferGBK,"GBK"); 7 System.out.println("gbkString = new String bufferGBK GBK : "+gbkString); 8 9 String utf8String =new String(bufferGBK,"utf-8"); 10 System.out.println("utf8String = new String bufferGBK utf8 : "+utf8String); 11 12 byte[] utfFromStr = utf8String.getBytes("utf-8"); 13 System.out.println("utf8String getBytes utf-8 : "+printHexBinary(utfFromStr)); 14 15 byte[] gbkFromStr = utf8String.getBytes("GBK"); 16 System.out.println("utf8String getBytes GBK : "+printHexBinary(gbkFromStr)); 17 18 byte[] isoFromStr = utf8String.getBytes("ISO-8859-1"); 19 System.out.println("utf8String getBytes ISO-8859-1 : "+printHexBinary(isoFromStr)); 20 21 String isoString =new String(bufferGBK,"ISO-8859-1"); 22 System.out.println("isoString = new String bufferGBK ISO-8859-1 : "+isoString); 23 24 utfFromStr = isoString.getBytes("utf-8"); 25 System.out.println("isoString getBytes utf-8 : "+printHexBinary(utfFromStr)); 26 27 gbkFromStr = isoString.getBytes("GBK"); 28 System.out.println("isoString getBytes GBK : "+printHexBinary(gbkFromStr)); 29 30 isoFromStr = isoString.getBytes("ISO-8859-1"); 31 System.out.println("isoString getBytes ISO-8859-1 : "+printHexBinary(isoFromStr));