• 字符编码


    编码:字符串到字节

    package com.sxt.io;
    
    import java.io.File;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    
    /**
     * 编码: 字符串-->字节
     * @author 
     *
     */
    public class ContentEncode {
    
        public static void main(String[] args) throws IOException {
            String msg ="努力学习a";
            //编码: 字节数组
            byte[] datas = msg.getBytes();  //默认使用工程的字符集
            System.out.println(datas.length);
            
            //编码: 其他字符集
            datas = msg.getBytes("UTF-16LE");
            System.out.println(datas.length);
            
            datas = msg.getBytes("GBK");
            System.out.println(datas.length);        
            
        }
    
    }

    解码:字节到字符串

    package com.sxt.io;
    
    import java.io.UnsupportedEncodingException;
    
    /**
     * 解码: 字节->字符串
     * @author
     *
     */
    public class ContentDecode {
    
        public static void main(String[] args) throws UnsupportedEncodingException {
            String msg ="努力学习a";
            //编码: 字节数组
            byte[] datas = msg.getBytes();  //默认使用工程的字符集
            
            //解码: 字符串 String​(byte[] bytes, int offset, int length, String charsetName)
            msg = new String(datas,0,datas.length,"utf8");
            System.out.println(msg);
            
            
            //乱码: 
            //1)、字节数不够
            msg = new String(datas,0,datas.length-2,"utf8");
            System.out.println(msg);
            msg = new String(datas,0,datas.length-1,"utf8");
            System.out.println(msg);
            
            //2)、字符集不统一
            msg = new String(datas,0,datas.length-1,"gbk");
            System.out.println(msg);
            
        }
    
    }
  • 相关阅读:
    平衡树板子
    51nod1201 整数划分
    时态同步[ZJOI2007]
    玉米田Corn Fields
    中国象棋[AHOI2009]
    孤岛营救与汽车加油行驶问题
    运输问题
    航空路线问题(dp解法)
    最小路径覆盖
    后缀排序(后缀数组初探
  • 原文地址:https://www.cnblogs.com/jiefangzhe/p/11302135.html
Copyright © 2020-2023  润新知