zoukankan      html  css  js  c++  java
  • 字符编码

    编码:字符串到字节

    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);
            
        }
    
    }
  • 相关阅读:
    WPF项目学习.一
    AtCoder Beginner Contest 210 A~D 题解
    P7715 「EZEC-10」Shape 题解
    P6216 回文匹配 题解
    字符串学习笔记
    #2742. 「JOI Open 2016」销售基因链
    树状数组学习笔记
    2021 省选游记
    AtCoder Beginner Contest 196 E
    AtCoder Regular Contest 113 A~D题解
  • 原文地址:https://www.cnblogs.com/jiefangzhe/p/11302135.html
Copyright © 2011-2022 走看看