编码:字符----》二进制;
解码:二进制----》字符;
计算机存储的都是二进制。
public static void main(String[] args) throws UnsupportedEncodingException {
String str = "努力";
//编码 char--->byte 默认使用gbk编码
byte[] data = str.getBytes();
//解码 byte-->char 默认使用gbk
str = new String(data);
System.out.println("---------解码编码方式均为默认,不会乱码----------------");
System.out.println(str);
//使用utf-8编码
data=str.getBytes("utf-8");
//不统一出现乱码:使用默认gbk解码
str = new String(data);
System.out.println("---------编码用的utf-8,解码默认gbk,出现乱码----------------");
System.out.println(str);
//使用utf-8编码
byte[] data2 = "努力".getBytes("utf-8");
//解码 使用utf-8,指定统一的解码方式
str = new String(data2,"utf-8");
System.out.println("---------编码用的utf-8,解码也用的utf-8,不会乱码----------------");
System.out.println(str);
//因字节数不完整出现乱码
System.out.println("---------因字节数不完整出现乱码----------------");
System.out.println(new String(data,0,3));
}
运行结果如下: