java基础常识指南

编码与解码

编码:把字符按照字符集编码成字节。

解码:把字节按照指定字符集解码成字符。

字符编码使用的字符集,和解码使用的字符集必须一致。

英文,数字一般不会乱码,因为很多字符集都兼容了ASCLL编码。

import java.io.UnsupportedEncodingException;

public class Main {
    public static void main(String[] args) throws UnsupportedEncodingException {
        //编码
        String s="a啊b";
        byte[] bytes=s.getBytes();//按照平台字符集(utf-8)进行编码

        byte[] bytes1=s.getBytes("GBK");

        //解码
        String s1=new String(bytes);

        String s2=new String(bytes1);//乱码
    
        String s3=new String(bytes1,"GBK");
    
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
    }
}
posted @ 2023-11-13 21:30  White_Sheep  阅读(6)  评论(0编辑  收藏  举报