在正常javaweb开发中经常会发现字符转换的需求,会存在中文字符转换乱码的现象,如何解决以及其转换原理我至今懵懵懂懂,于是专门写了个测试代码进行尝试,总算理清了编码,先上结论,总结如下:
utf8中存放有各种语言编码,当前主流开发中会使用utf8进行编码解码,该方式不会产生乱码,产生乱码有以下几种情况
1、gbk(中文)、iso-8859-1(无中文)等其他方式进行编码,则只能用其对应方式进行解码,否则为乱码
2、使用utf8进行编码用其他方式解码则会导致乱码,需进行一次转换
3、使用无对应字符(中文)的字符集(iso-8859-1)编码会导致乱码,且无法还原解码
以下是针对以上情况的代码测试
1.如何编码就如何解码
1 2 3 4 5 6 7 8 9
|
@Test public void test0() { String test = "测试"; System.out.println(Arrays.toString(test.getBytes(StandardCharsets.UTF_8))); System.out.println(new String(test.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8)); }
|
1 2 3 4 5 6 7 8 9
|
@Test public void test1() throws UnsupportedEncodingException { String test = "测试"; System.out.println(Arrays.toString(test.getBytes("gbk"))); System.out.println(new String(test.getBytes("gbk"), "GBK")); }
|
- utf8编码 - 错误形式解码
1 2 3 4 5 6 7 8 9
|
@Test public void test2() throws UnsupportedEncodingException { String test = "测试"; System.out.println(Arrays.toString(test.getBytes(StandardCharsets.UTF_8))); System.out.println(new String(test.getBytes(StandardCharsets.UTF_8), "gbk")); }
|
正确做法,按错误的解码形式(gbk)作为中转,将其按错误形式(gbk)重新还原编码(utf8-encode),再使用utf8进行一次正确解码(utf8-decode)即可得到原来的字符
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
@Test public void test3() throws UnsupportedEncodingException { String test = "测试"; String test_gbk_utf8 = new String(test.getBytes(StandardCharsets.UTF_8), "gbk"); System.out.println(test_gbk_utf8); String test_utf8_gbk = new String(test_gbk_utf8.getBytes("gbk"), StandardCharsets.UTF_8); System.out.println(test_utf8_gbk);
}
|
3.无对应字符编码
1 2 3 4 5 6
| @Test public void test4() throws UnsupportedEncodingException { String test = "测试"; System.out.println(Arrays.toString(test.getBytes(StandardCharsets.ISO_8859_1))); System.out.println(new String(test.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.ISO_8859_1)); }
|
该情况下即使使用原先的编码方式进行解码也无法还原字符了,属于不可逆的状态