字节序的编码问题——乱码是怎样产生的

来源:互联网 发布:更新软件下载 编辑:程序博客网 时间:2024/06/07 19:26
一 代码
package com.imooc.io;public class EncodeDemo {/** * @param args */public static void main(String[] args)throws Exception {// TODO Auto-generated method stubString s="慕课ABC";//转换为字节序列,用的是项目默认的编码gbkbyte[] bytes1 = s.getBytes();for(byte b:bytes1){//把字节(转换成了int)以16进制的方式显示System.out.print(Integer.toHexString(b&0xff)+" ");}System.out.println();byte[] bytes2=s.getBytes("gbk");//gbk编码中文占用2个字节,英文占用1个字节for(byte b:bytes2){//把字节(转换成了int)以16进制的方式显示System.out.print(Integer.toHexString(b&0xff)+" ");}System.out.println();byte[] bytes3=s.getBytes("utf-8");//utf-8编码中文占用3个字节,英文占用1个字节for(byte b:bytes3){//把字节(转换成了int)以16进制的方式显示System.out.print(Integer.toHexString(b&0xff)+" ");}System.out.println();byte[] bytes4=s.getBytes("utf-16be");//Java是双字节编码 utf-16be//utf-16be 中文占用2个字节,英文占用2个字节for(byte b:bytes4){//把字节(转换成了int)以16进制的方式显示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);/* * 文本文件就是字节序列 * 可以是任意编码的字节序列 * 如果我们在中文机器上直接创建文本文件,那么该文本文件只认识ansi编码 * */}}

二 运行结果

三 项目默认编码是gbK

四 小结
gbk编码中文占用2个字节,英文占用1个字节。
utf-8编码中文占用3个字节,英文占用1个字节
utf-16be 中文占用2个字节,英文占用2个字节
当你的字节序列是某种编码时,这个时候想把字节序列变成字符串,也需要用这种编码方式,否则会出现乱码
文本文件就是字节序列
可以是任意编码的字节序列
如果我们在中文机器上直接创建文本文件,那么该文本文件只认识ansi编码