292 字符串中的编码解码问题
> 我们采用IDEA平台编写代码
编码 | |
byte[] getBytes(); | 使用平台的默认字符集,将该String编码为一系列字节,将结果存储到新的 字节数组 |
byte[] getBytes(String charsetName); | 使用指定的字符集,将该String编码为一系列字节,将结果存储到 新的字节数组 |
解码 | |
String(byte[] bytes); | 使用平台默认的字符集,解码指定的字符数组,构造新的String |
String(byte[] bytes,String charsetName); | 使用指定的字符集,解码指定的字符数组,构造新的String |
【代码思路】
试用以上4个方法
【小结】
//用指定字符集编码
String s = "中国";
byte[] b = s.getBytes("UTF-8");
System.out.println(Arrays.toString(b));
--------------------------------------------------------------
1 package e292; 2
3 import java.io.UnsupportedEncodingException;
4 import java.nio.charset.StandardCharsets;
5 import java.util.Arrays;6
7 public class StringDemo {
8 public static void main(String[] args) throws UnsupportedEncodingException {
9 //用默认字符集编码
10 String s11 = "中国";
11 byte[] b11 = s11.getBytes();
12 System.out.println("12\t" + Arrays.toString(b11));//[-28, -72, -83, -27, -101, -67]
13
14 //用指定字符集编码
15 String s12 = "中国";
16 byte[] b12 = s12.getBytes("UTF-8");
17 System.out.println("17\t" + Arrays.toString(b12));
18
19 String s13 = "中国";
20 byte[] b13 = s13.getBytes("GBK");
21 System.out.println("21\t" + Arrays.toString(b13));
22
23 // 解码,用默认字符集
24 String s21 = "中国";
25 byte[] b21 = s21.getBytes();
26 String ss21 = new String(b21);
27 System.out.println("27\t" + ss21);
28
29 // 解码,用指定字符集
30 String s22 = "中国";
31 byte[] b22 = s22.getBytes();
32 String ss22 = new String(b22, "UTF-8");
33 System.out.println("33\t" + ss22);
34
35 String s23 = "中国";
36 byte[] b23 = s23.getBytes();
37 String ss23 = new String(b23, "GBK");
38 System.out.println("38\t" + ss23);
39 }
40 }
41 /*
42 12 [-28, -72, -83, -27, -101, -67]
43 17 [-28, -72, -83, -27, -101, -67]
44 21 [-42, -48, -71, -6]
45 27 中国
46 33 中国
47 38 涓浗
48 */