字符编码

编码:字符串到字节

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);
        
    }

}

 

posted on 2019-08-05 11:44  JieFangZhe  阅读(118)  评论(0编辑  收藏  举报

导航