import java.io.UnsupportedEncodingException;
public class EncodeDemo {
public static void main(String[] args) throws Exception {
String s="慕课ABC";
byte[] bytes1 = s.getBytes();//转换成字节序列,使用项目默认的的编码
for(byte b : bytes1) {
//把字节转换成int 以16进制的方式显示(int占4个字节)
System.out.print(Integer.toHexString(b & 0xff)+" ");
}
System.out.println();
byte[] bytes2 = s.getBytes("gbk");
//gbk编码中文占用两个字节,英文占用一个字节
for (byte b : bytes2) {
System.out.print(Integer.toHexString(b & 0xff)+" ");
}
System.out.println();
byte[] bytes3 = s.getBytes("utf-8");
//utf-8编码中中文占用3个字节,英文占用一个字节
for(byte b : bytes3) {
System.out.print(Integer.toHexString(b & 0xff) + " ");
}
System.out.println();
byte[] bytes4 = s.getBytes("utf-16be");
//utf-16be编码中中文占用2个字节,英文占用2个字节
for(byte b : bytes4) {
System.out.print(Integer.toHexString(b & 0xff) + " ");
}
System.out.println();
/*
* 当你的字节序列是某种编码时,这个时候想把字节序列变成字符串,也需要使用这种编码,否则会出现乱码
*/
String str1 = new String(bytes4);//项目默认的编码
System.out.println(str1);
String str2 = new String(bytes4, "utf-16be");
System.out.println(str2);
//文本文件就是字节序列,可以是任意编码的字节序列,会自动转换编码
}
}