编码 : 字符串---->字节
String msg ="JAVA编码与解码";
//编码: 字节数组
byte[] datas = msg.getBytes(); //默认使用工程的字符集
System.out.println(datas.length);
//编码: 其他字符集
datas = msg.getBytes("UTF-16LE");
System.out.println(datas.length);
datas = msg.getBytes("GBK");
System.out.println(datas.length);
解码 : 字节----->字符串
String msg ="JAVA编码与解码";
//编码: 字节数组
byte[] datas = msg.getBytes(); //默认使用工程的字符集
//解码: 字符串 String(byte[] bytes, int offset, int length, String charsetName)
msg = new String(datas,0,datas.length,"utf8");
System.out.println(msg);
发生乱码的原因: 1)字节数不够 2)字符集不统一
//1)、字节数不够
msg = new String(datas,0,datas.length-2,"utf8");
System.out.println(msg);
msg = new String(datas,0,datas.length-1,"utf8");
System.out.println(msg);
//2)、字符集不统一
msg = new String(datas,0,datas.length-1,"gbk");
System.out.println(msg);