03 字符集、编码解码、乱码解决

字符集

  • ASCLL码不包含中文
  • GBK是中文专用
  • Unicode国际通用
  • UTF-8 可变长编码
  • ISO 8859-1

编码解码

编码:字符转二进制,便于传输

示例:

String str = "我是一个好人";

byte[] dates = str.getBytes();//括号汇总可选填字符集名称,表示按某种字符集编码

解码:将二进制机器码转化为字符,便于阅读

示例:将网络上传来的数据转换为字符串

str = new String(dates); //str与dates为上文中的变量。new String的方法请查看String类的构造方法。

乱码解决

转码时导致乱码可能有两种原因:

1.接收的数据不完整

如:str = new String(bytes,0,bytes.length-1);

2.字符集不统一

如:将中文使用ISO-8859-1解码导致乱码

str = new String(sBytes,"ISO-8859-1");

本文代码

public class Charset
{
	public static void main(String[] args){
		String str = "我是好人";
		byte[] sBytes = str.getBytes();//按默认字符集解码
		System.out.println(sBytes.length);
		for(byte b : sBytes){
			System.out.println(b);
		}
		System.out.println("------------------");
		//乱码原因
		//丢失数据
		str = new String(sBytes,0,sBytes.length-1);
		System.out.println(str);//输出结果为:我是好?
		//编码错误
		try{
			str = new String(sBytes,"ISO-8859-1");
		}catch(Exception e){
			System.err.println("解码异常!");
		}
		System.out.println(str);//输出结果:?????
	}
}

  

posted @ 2019-11-21 22:07  Scorpicat  阅读(186)  评论(0编辑  收藏  举报