1 package edzy.nio; 2
3 import org.junit.Test; 4
5 import java.io.UnsupportedEncodingException; 6 import java.nio.ByteBuffer; 7 import java.nio.CharBuffer; 8 import java.nio.charset.CharacterCodingException; 9 import java.nio.charset.Charset; 10 import java.nio.charset.CharsetDecoder; 11 import java.nio.charset.CharsetEncoder; 12
13
14 public class Coder { 15
16 @Test 17 public void demo() throws CharacterCodingException, UnsupportedEncodingException { 18
19 //獲取GBK字符集對象
20 Charset gbk = Charset.forName("GBK"); 21
22 //獲取編碼器
23 CharsetEncoder gbkEn = gbk.newEncoder(); 24
25 //獲取解碼器
26 CharsetDecoder gbkDe = gbk.newDecoder(); 27
28 //字符緩衝
29 CharBuffer buffer = CharBuffer.allocate(1024); 30 buffer.put("這是一個java-nio字符集的測試"); 31 buffer.flip(); 32
33 //編碼器編碼
34 ByteBuffer buf = gbkEn.encode(buffer); 35 for (byte b : buf.array()){ 36 System.out.println(b); 37 } 38
39
40 //解碼器解碼
41 CharBuffer chars = gbkDe.decode(buf); 42 System.out.println(chars.toString()); 43
44
45 //亂碼
46 buf.flip(); 47 Charset utf8 = Charset.forName("UTF-8"); 48 CharBuffer text = utf8.decode(buf); 49 System.out.println(text.toString()); 50
51
52 } 53
54
55 }