nio缓冲对象
Posted kill-9
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nio缓冲对象相关的知识,希望对你有一定的参考价值。
1 package edzy.nio;
2
3 import org.junit.Test;
4
5 import java.nio.ByteBuffer;
6
7 public class ByteNIO {
8
9 @Test
10 public void byteBuf(){
11 ByteBuffer buf = ByteBuffer.allocate(1024);
12 System.out.println("---allocate缓冲---");
13 System.out.println(buf.position());
14 System.out.println(buf.limit());
15 System.out.println(buf.capacity());
16
17 System.out.println("---put存数据---");
18 String text = "NIO";
19 buf.put(text.getBytes());
20 System.out.println(buf.position());
21 System.out.println(buf.limit());
22 System.out.println(buf.capacity());
23
24 System.out.println("---flip切换到读模式---");
25 buf.flip();
26 System.out.println(buf.position());
27 System.out.println(buf.limit());
28 System.out.println(buf.capacity());
29
30
31 System.out.println("---get读数据---");
32 byte[] dest = new byte[buf.limit()];
33 buf.get(dest);
34 System.out.println(buf.position());
35 System.out.println(buf.limit());
36 System.out.println(buf.capacity());
37 System.out.println(new String(dest));
38
39
40 System.out.println("---rewind重新读数据---");
41 buf.rewind();
42 System.out.println(buf.position());
43 System.out.println(buf.limit());
44 System.out.println(buf.capacity());
45
46 System.out.println("---clear清除指针---");
47 buf.clear();
48 System.out.println(buf.position());
49 System.out.println(buf.limit());
50 System.out.println(buf.capacity());
51
52
53 }
54
55 @Test
56 public void mark(){
57
58 ByteBuffer buf = ByteBuffer.allocate(100);
59 String str = "mvn compile";
60 buf.put(str.getBytes());
61 buf.flip();
62 byte[] dest = new byte[buf.limit()];
63 buf.get(dest,0,4);
64 System.out.println(new String(dest,0,4));
65 System.out.println(buf.position());
66
67 //mark标记
68 buf.mark();
69 buf.get(dest,4,4);
70 System.out.println(new String(dest,0,8));
71 System.out.println(buf.position());
72
73 //指针设置为mark标记所在的位置
74 buf.reset();
75 System.out.println(buf.position());
76
77 //是否有下一个元素
78 if(buf.hasRemaining()){
79 //缓冲区中的剩余元素数
80 System.out.println(buf.remaining());
81 }
82 }
83 @Test
84 public void direct(){
85 ByteBuffer buf = ByteBuffer.allocate(100);
86 //直接字节缓冲区
87 ByteBuffer bufd = ByteBuffer.allocateDirect(100);
88 System.out.println(buf.isDirect());
89 System.out.println(bufd.isDirect());
90 }
91 }
以上是关于nio缓冲对象的主要内容,如果未能解决你的问题,请参考以下文章