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