其他分享
首页 > 其他分享> > NIO(三) - 字符节(转换)

NIO(三) - 字符节(转换)

作者:互联网

package com.xbb.demo;

import org.junit.Test;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

/**
 * 字符节
 * 编码:字符串 -> 字节数组
 * 解码:字节数组  -> 字符串
 */
public class EncodingFormatDemo {

    @Test
    public void normal(){
        CharBuffer cBuf = CharBuffer.allocate(1024);
        cBuf.put("中国");
        cBuf.flip();
        System.out.println(cBuf.get(1));
    }

    @Test
    public void enAndDn() throws Exception{
        // 设置编码格式
        Charset charset = Charset.forName("GBK");
        CharsetEncoder charsetEncoder = charset.newEncoder();
        CharsetDecoder charsetDecoder = charset.newDecoder();
        String luckStr = "中国,祝福你";
        CharBuffer cBuf = CharBuffer.allocate(1024);
        cBuf.put(luckStr);
        cBuf.flip();

        ByteBuffer buf = charsetEncoder.encode(cBuf);
        CharBuffer cBuf2 = charsetDecoder.decode(buf);
        System.out.println(cBuf2.toString());
    }
}

标签:字符,转换,NIO,java,CharBuffer,charset,import,cBuf,nio
来源: https://blog.csdn.net/jinjianghai/article/details/98035822