nio的字符集对象
2018-09-12 14:21 kill-9 阅读(219) 评论(0) 编辑 收藏 举报 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 }