JAVA学习随笔(4)-编码基本概念随笔

1.JBK编码,中文占用2字节,英文占用1字节。
2.UTF-8编码,中文占用3字节,英文占用1字节。
3.java是双字节编码,是utf-16be编码,中文占用2字节,英文也占用2字节。
当你的字节是某种编码时,这时想把你的字节编程字符串,也需要使用对应的棉麻方式,否则可能出现乱码问题。
4.文本文件就是字节序列,可以是任意编码的字节序列。如果在中文机器上创建文本文件.txt,该文件默认只认ansi编码,但它可以识别任意格式的编码文件

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

public class ByteTest {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String s = "慕课ABC";

        byte[] defualtByte = s.getBytes();
        System.out.println("默认编码:");
        for(byte b:defualtByte)
        {
            System.out.print(Integer.toHexString(b & 0xff)+" ");
        }

        System.out.println("\ngbk编码");
        byte[] gbkByte = s.getBytes("gbk");
        for(byte b:gbkByte)
        {
            System.out.print(Integer.toHexString(b & 0xff)+" ");
        }

        System.out.println("\nutf-8编码:");
        byte[] utf8Byte = s.getBytes("utf-8");
        for(byte b:utf8Byte)
        {
            System.out.print(Integer.toHexString(b & 0xff)+" ");
        }

        System.out.println("\nutf-16be编码:");
        byte[] utf16Byte = s.getBytes("utf-16be");
        for(byte b:utf16Byte)
        {
            System.out.print(Integer.toHexString(b & 0xff)+" ");
        }

        String strDefualt = new String(utf16Byte);
        System.out.println("\n默认转换回字符串结果:"+strDefualt);

        String strUtf16 = new String(utf16Byte,"utf-16be");
        System.out.println("utf-16be格式转换回字符串结果:"+strUtf16);

        System.out.println("java默认编码格式:"+Charset.defaultCharset());

    }

代码结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值