编码解码
编码(encode): 由字节到字符
解码(decode): 由字符到字节
在编码解码过程中使用了字符集。
编码解码测试
code
import java.io.UnsupportedEncodingException;
/**
* 编码:字符串-->字节数组
* 解码:字节数组-->字符串
* @author dxt
*
*/
public class TestEncode {
public static void main(String[] args) throws UnsupportedEncodingException{
String msg = "茅屋为秋风所破歌";
//1. 编码: getBytes(): 对msg依据不同字符集进行编码, 字符串-->字节
byte[] datas = msg.getBytes();
//默认使用工程字符集进行编码,UTF-8中每个字占3个字节,所以length = 3 x 8 = 24
System.out.println(datas.length);
//编码:编码成其他字符集
datas = msg.getBytes("GBK"); //GBK中每个汉字占2个字节,字母占1个字节
System.out.println(datas.length);
//2. 解码
msg = new String(datas, 0, datas.length, "GBK");
System.out.println(msg);
//3. 乱码
//3.1 字节数不够
msg = new String(datas, 0, datas.length-2, "GBK");
System.out.println(msg);
msg = new String(datas, 0, datas.length-1, "GBK");
System.out.println(msg);
//3.2 字符集不同一
msg = new String(datas); //默认使用的字符集为工程字符集(UTF-8)
System.out.println(msg);
}
}
result