1-1 文件的编码
package com.yxt.haha;
import java.io.UnsupportedEncodingException;
public class EncodeDemo {
/**
* @param args
* @throws UnsupportedEncodingException
*/
public static void main(String[] args) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
String s="慕课AB";
byte[] bytes1=s.getBytes();//装换成字节序列用的是项目默认的编码gbk
for (byte b : bytes1) {
//把字节(转换成了int)以16进制方式显示
System.out.print(Integer.toHexString(b&0xff)+" ");//int是32位的,前24位都是0无意义,所以只留下后8位
}
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个字节,英文占用1个字节
for (byte b : bytes3) {
System.out.print(Integer.toHexString(b&0xff)+" ");
}
System.out.println();
//java是双字节编码,utf-16be
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);//系统默认gbk
System.out.println(str1);
String str2=new String(bytes4,"utf-16be");
System.out.println(str2);
/*文本文件就是字节序列
* 可以使认识编码的字节序列
* 如果我们在中文机器中直接创建文本文件,那么该文本文件只认识ansi编码
* 联通、联这是一种巧合,他们正好符合了utf-8编码的规则
*/
}
}