- GBK编码 中文占两个字节,英文占一个字节
- UTF-8编码 中文占三个字节,英文占一个字节
- UTF-16BE编码 中文占两个字节,英文占两个字节
- 字符序列是某种编码时,当需要将字符序列变成字符串需要设这为这种编码,否则会出现乱码
package test;
import java.io.UnsupportedEncodingException;
/**
* 文件编码 探讨
*
* @author Mr.wang
*
*/
public class FileCodeDemo {
public static void main(String[] args) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
/*创建一个中英文组合字符串*/
String hello = "你好Hello";
byte[] bytes = hello.getBytes("UTF-8");
for(byte b:bytes) {
System.out.print(Integer.toHexString(b & 0xFF) + " ");//把字节转(换成Int)16进制的表示
}
/**
* 运行结果 e4 bd a0 e5 a5 bd 48 65 6c 6c 6f
*
* 结论:UTF-8编码 中文占三个字节,英文占一个字节
*
* */
byte[] bytes1 = hello.getBytes("GBK");
System.out.println();
for(byte b:bytes1) {
System.out.print(Integer.toHexString(b & 0xFF) + " ");//把字节转(换成Int)16进制的表示
}
/**
* 运行结果 c4 e3 ba c3 48 65 6c 6c 6f
*
* 结论:GBK编码 中文占两个字节,英文占一个字节
*
* */
byte[] bytes3 = hello.getBytes("UTF-16BE");
System.out.println();
for(byte b:bytes3) {
System.out.print(Integer.toHexString(b & 0xFF) + " ");//把字节转(换成Int)16进制的表示
}
/**
* 运行结果 4f 60 59 7d 0 48 0 65 0 6c 0 6c 0 6f
*
* 结论:UTF-16BE编码 中文占两个字节,英文占两个字节
*
* */
System.out.println();
String str = new String(bytes3);
String str2 = new String(bytes3,"UTF-16BE");
System.out.println("用系统默认编码:" + str);
System.out.print("用字符设置的编码:" + str2);
/**
* 运行结果 :
* 用系统默认编码: O`Y} H e l l o
* 用字符设置的编码:你好Hello
*
* 结论:当你的字符序列是某种编码时,当需要将字符序列变成字符串需要设这为这种编码,否则会出现乱码!
*
* */
}
}
备注:
关于 &0xFF:
在32位的电脑中数字都是以32格式存放的,如果是要求一个byte(8位)类型的数字,对于int这种32位的整形,高24位具有随机性(从所有的数字形式来看,前面的24位取值并不确定,我把它视为具有一定的随机性,比如int型的整数,高24位的取值都是不确定的。),低8位 才是实际的数据。 java.lang.Integer.toHexString() 方法的参数是int(32位)类型,如果输入一个byte(8位)类型的数字,这个 方法会把这个数字的高24为也看作有效位,这就必然导致错误,使用& 0XFF操作,可以把高24位置0以避免这样错误 的发生。