前言
在开发过程中,我们可能会遇到Java各种编码格式之间的转换问题。下面我们来研究下UTF-8和GBK等编码格式之间的相互转化。
实践
在进行编码转换时,我们用ISO-8859-1编码来接受和保存数据,并转换为相应编码。
为什么采用ISO-8859-1编码作为中间转存方案呢?
下面我们通过程序验证:
通过ISO-8859-1转存:
public static void test(String str1,String encode) throws UnsupportedEncodingException { System.out.println("字符串:"+str1); //将str转为原编码字节流 byte[] byteArray1=str1.getBytes(encode); System.out.println(byteArray1.length); //转换为一个ISO-8859-1的字符串 String str2=new String(byteArray1,"ISO-8859-1"); System.out.println("转成ISO-8859-1:"+str2); //转回为byte数组 byte[] byteArray2=str2.getBytes("ISO-8859-1"); System.out.println(byteArray2.length); //重新用目标编码格式编码 String str3=new String(byteArray2,encode); System.out.println("字符串:"+str3); } public static void main(String[] args) throws UnsupportedEncodingException { String str1="你好"; String str2="你好呀"; test(str1,"UTF-8"); test(str2,"UTF-8"); }
运行结果:
字符串:你好 6 转成ISO-8859-1:ä½ å¥½ 6 字符串:你好 字符串:你好呀 9 转成ISO-8859-1:ä½ å¥½å‘€ 9 字符串:你好呀
通过GBK转存:
public static void test(String str1,String encode) throws UnsupportedEncodingException { System.out.println("字符串:"+str1);