目录
一、码表
1.ASCII表
2.GBK:
Windows系统默认的码表;也是中国的码表;一个中文以两个字节的形式储存;一个字符是两个字节;idea、Unicode的UTF-8编码格式:一个字符是三个字节。
二、字符流的编码与解码
1.编码方法
- byte[]getBytes(): 使用默认的码表将该String编码为相应的字节,再存储到新的字节数组中
- byte[]getBytes(String charsetName): 使用默认码表将该String编码为一系列字节,再存储到新的字节数组中
2.解码方法
- String(byte[] bytes): 使用默认码表解析指定的字节数组,构造新的String
- String(byte[] bytes,String charsetName): 通过指定的码表解析指定的字节数组,构造新的String
3.代码演示
(1)编码
private static void method1() throws UnsupportedEncodingException {
//方法一:使用默认编码格式(UTF-8)
String s = "我爱中国";
byte[] bytes1 = s.getBytes();
System.out.println(Arrays.toString(bytes1));//将字符串内容编码后,存储在字节数组中,再使用Arrays.toString方法打印数组中内容
//方法二:指定编码格式(GBK)
byte[] bytes2 = s.getBytes("GBK");
System.out.println();
System.out.println(Arrays.toString(bytes2));
}
(2)解码
private static void method2() throws UnsupportedEncodingException {
//方法一:使用默认解码格式(UTF-8)
byte[] byte1 = {-26, -120, -111, -25, -120, -79, -28, -72, -83, -27, -101, -67};
byte[] byte2 = {-50, -46, -80, -82, -42, -48, -71, -6};
String s1 = new String(byte1);
System.out.println(s1);
//方法二:使用指定解码格式(GBK)
String s2 = new String(byte2, "GBK");
System.out.println(s2);
}