字符串中的编码解码问题

编码方法:

          1. public byte[] getBytes​()
            使用平台的默认字符集将该String编码为一系列字节,将结果存储到新的字节数组中。
          2.
                public byte[] getBytes​(String charsetName)
                                                throws UnsupportedEncodingException
              使用命名的字符集将这个String编码成一个字节序列,将结果存储到一个新的字节数组中。
 
解码方法:
      
        1,public String​(byte[] bytes)
        通过使用平台的默认字符集解码指定的字节数组来构造新的String 。 新的String的长度是字符集的函数,因此可能不等于字节数组的长度。
        2,
          public String​(byte[] bytes,String charsetName) throws UnsupportedEncodingException
            构造一个新的String由指定用指定的字节的数组解码charset 。 新的String的长度是字符集的函数,因此可能不等于字节数组的长度。
 
package com.io.liushuaishuai;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class StringDemo {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String s = "中国";
        
//        编码
        //byte[] bys1 = s.getBytes();//默认编码方式为utf-8:[-28, -72, -83, -27, -101, -67]
        byte[] bys2 = s.getBytes("GBK");//[-42, -48, -71, -6]
        //System.out.print(Arrays.toString(bys1));


//        解码
//        String ss = new String(bys1);//中国
//        String sss = new String(bys1,"utf-8");//中国
//        String gbk = new String(bys1,"GBK");//涓�浗:由于编码方式为utf-8,解码时用GBK,出现乱码
        String gbk = new String(bys2,"GBK");中国
//        System.out.println(ss);
//        System.out.println(sss);
        System.out.println(gbk);

    }
}
 
原文地址:https://www.cnblogs.com/lsswudi/p/11423865.html