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 }
相關文章
相關標籤/搜索