EncodeDemo.java package cn.xuzihui;public class EncodeDemo {public static void main(String[] args) throws Exception {// TODO Auto-generated method stubString s = "中国ABC";//转换成字符序列用的是项目默认的编码GBKbyte[] byt
package cn.xuzihui;
public class EncodeDemo {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String s = "中国ABC";
//转换成字符序列用的是项目默认的编码GBK
byte[] byte1 = s.getBytes();
for(byte b:byte1) {
//把字节(转换成了int)以16进制的方式显示
System.out.print(Integer.toHexString(b & 0xff)+" ");
//输出结果: d6 d0 b9 fa 41 42 43
}
System.out.println();
byte[] byte2 = s.getBytes("gbk");
//gbk 编码中文占用2个字节,英文占用一个字节
for (byte b : byte2) {
System.out.print(Integer.toHexString(b & 0xff)+" ");
//输出结果: d6 d0 b9 fa 41 42 43
}
System.out.println();
byte[] byte3 = s.getBytes("utf-8");
//utf-8 编码中文占用3个字节,英文占用一个字节
for (byte b : byte3) {
System.out.print(Integer.toHexString(b & 0xff)+" ");
//输出结果: e4 b8 ad e5 9b bd 41 42 43
}
System.out.println();
//java是双字节编码 utf-16be
byte[] byte4 = s.getBytes("utf-16be");
//utf-16be 编码中文占用2个字节,英文也占用2个字节
for (byte b : byte4) {
System.out.print(Integer.toHexString(b & 0xff)+" ");
//输出结果: 4e 2d 56 fd 0 41 0 42 0 43
}
System.out.println();
/*
* 当你的字节序列是某种编码时,这个时候想把字节序列变成字符串,
* 也需要用这种编码方式,否则会出现乱码
*/
String str1 = new String(byte4);//用项目默认编码
System.out.println(str1); //输出为乱码
String str2 = new String(byte4, "utf-16be");
System.out.println(str2);
//输出结果: 中国ABC
/*
* 文本文件就是字节序列,可以是任意编码的字节序列
* 如果我们在中文机器上直接创建文本文件,那么该文本文件只认识ansi编码
*/
}
}
