1. 程式人生 > >nio學習之編碼與解碼

nio學習之編碼與解碼

package nio;

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

//nio字符集編碼
public class testCharacter {
    public static void main(String[] a){
       //設定編碼器
        Charset charset = Charset.forName("GBK");
        //獲取緩衝器
        CharBuffer charBuffer = CharBuffer.allocate(1024);
        charBuffer.put("skdfns史可法你00");
        //編碼
        charBuffer.flip();
        ByteBuffer byteBuffer = charset.encode(charBuffer);
        for(int i = 0;i < byteBuffer.limit();i ++){
            System.out.println(byteBuffer.get());
        }

        //解碼
        byteBuffer.flip();
        CharBuffer charBuffer1 = charset.decode(byteBuffer);
        for(int i = 0;i < charBuffer1.limit();i ++){
            System.out.println(charBuffer1.get());
        }
    }
}