gbk
gbk 编码中文占用2个字节,英文占用1个字节
1 2 3 4 5 6 7 8 9
| public static void main(String[] args) throws UnsupportedEncodingException { String s = "风间ABC"; byte[] bytes3 = s.getBytes("gbk"); for (byte b : bytes3) { System.out.print(Integer.toHexString(b & 0xff)+" "); } }
|
提示:& 0xff 保留后8位置(一个字节8位,int占4个字节,展示时前面24位去掉)
utf-8
utf-8 编码中文占用3个字节,英文占用1个字节
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public static void main(String[] args) throws UnsupportedEncodingException { String s = "风间ABC"; byte[] bytes1 = s.getBytes(); for (byte b : bytes1) { System.out.print(Integer.toHexString(b & 0xff)+" "); } byte[] bytes2 = s.getBytes("utf-8"); for (byte b : bytes2) { System.out.print(Integer.toHexString(b & 0xff)+" "); } }
|
utf-16be
java 是双字节编码 utf-16be,java 中一个字符占两个字节
java 一个字符是否可以放一个汉字?可以,gbk编码的汉字
1 2 3 4 5 6 7 8
| public static void main(String[] args) throws UnsupportedEncodingException { String s = "风间ABC"; byte[] bytes4 = s.getBytes("utf-16be"); for (byte b : bytes4) { System.out.print(Integer.toHexString(b & 0xff)+" "); } }
|
字节序列转字符串
当你的字节序列是某种编码时,这个时候想把字节序列变成字符串,
也需要用这种编码方式,否则会出现乱码
1 2 3 4 5 6 7 8
| public static void main(String[] args) throws UnsupportedEncodingException { String s = "风间ABC"; String str1 = new String(bytes4); System.out.println(str1);
String str2 = new String(bytes4, "utf-16be"); System.out.println(str2); }
|
项目间拷贝文件
文本文件就是字节序列,可以是任意编码格式
eclipse不同项目之间拷贝文件,编码不同会导致乱码,复制内容则会自动转换编码格式
完