一:编码:字符串---->字节
package com.wyj.two;import java.io.UnsupportedEncodingException;/*** 编码:字符串-->字节* * * @author 王永杰**/
public class Demo1_encode编码 {public static void main(String[] args) throws UnsupportedEncodingException {String mag = "性命生命使命";//编码:字节数组 在GBK中一个中文字符 占用两个字节 utf-8中一个中文字符占用3个字节byte dates[] = mag.getBytes();//默认使用工程字符集System.out.println(dates.length);//编码:改成其他字符集byte dates2[] = mag.getBytes("utf-8");System.out.println(dates2.length);}
}
二:解码:字节---->字符串
package com.wyj.two;import java.io.UnsupportedEncodingException;/*** 编码:字节-->字符串* * * @author 王永杰**/
public class Demo2_decode解码 {public static void main(String[] args) throws UnsupportedEncodingException {String mag = "性命生命使命";//编码:字节数组 在GBK中一个中文字符 占用两个字节 utf-8中一个中文字符占用3个字节byte dates[] = mag.getBytes();//默认使用工程字符集//解码 String(byte[] bytes, int offset, int length, String charsetName)mag = new String(dates,0,dates.length,"utf8");System.out.println(mag);}
}
三:常见乱码原因
//乱码://1:字节数不够mag = new String(dates,0,dates.length-2,"utf8");System.out.println(mag);//2:字符集不统一mag = new String(dates,0,dates.length,"gbk");System.out.println(mag);
如有疑惑欢迎留言