NIO基礎方法一

1.remaining();返回當前位置與limit之間得元素數。數組

int[] intArray={1,2,3,4};
        IntBuffer intBuffer=IntBuffer.wrap(intArray);
        intBuffer.limit(3);
        intBuffer.position(1);
        System.out.println(intBuffer.remaining());

 2.isDirect() 判斷是否爲直接緩衝區。spa

ByteBuffer byteBuffer=ByteBuffer.allocateDirect(100);
        System.out.println(byteBuffer.isDirect());

3.clear()還原緩衝區得狀態,是狀態,不是數據;好比將position=0.market丟失掉。code

byte[] byteArray=new byte[]{1,2,3};
        ByteBuffer byteBuffer=ByteBuffer.wrap(byteArray);
        byteBuffer.position(2);
        byteBuffer.limit(3);
        byteBuffer.mark();
        
        byteBuffer.clear();
        System.out.println("position:"+byteBuffer.position()+";limit:"+byteBuffer.limit());
        try {
            byteBuffer.reset();
        } catch (Exception e) {
            System.out.println("market已經丟失");
        }

4.flip() 向緩衝區寫入一些數據後,下一步直接讀取緩衝區中得數據以前,以改變limit與position得值。blog

byte[] byteArray=new byte[]{1,2,3};
        ByteBuffer byteBuffer=ByteBuffer.wrap(byteArray);
        byteBuffer.position(2);
        byteBuffer.mark();
        
        byteBuffer.flip();
        System.out.println("position:"+byteBuffer.position()+";limit:"+byteBuffer.limit());
        try {
            byteBuffer.reset();
        } catch (Exception e) {
            System.out.println("market已經丟失");
        }

 5.hasArray()判斷此緩衝區是否具備可訪問得底層實現數組。ip

ByteBuffer byteBuffer=ByteBuffer.allocate(100);
        byteBuffer.put((byte) 1);
        byteBuffer.put((byte) 2);
        System.out.println(byteBuffer.hasArray());
        
        ByteBuffer byteBuffer2=ByteBuffer.allocateDirect(100);
        byteBuffer2.put((byte) 1);
        byteBuffer2.put((byte) 2);
        System.out.println(byteBuffer2.hasArray());

6.hasRemaining() 判斷當前位置與限制之間是否有元素。ci

byte[] byteArray=new byte[]{1,2,3};
        ByteBuffer bytebuffer=ByteBuffer.wrap(byteArray);
        bytebuffer.limit(3);
        bytebuffer.position(2);
        System.out.println(bytebuffer.hasRemaining()+";"+bytebuffer.remaining());

7.rewind()  position置爲0,標記清除掉,limit不變。rem

8.clear() position置爲0,limit=capacity,market=-1.清除緩衝區得狀態。get

9.List.toArrat(T[])  轉成數組。it

ByteBuffer buffer1=ByteBuffer.wrap(new byte[]{'a','b','c'});
        ByteBuffer buffer2=ByteBuffer.wrap(new byte[]{'x','y','z'});
        ByteBuffer buffer3=ByteBuffer.wrap(new byte[]{'1','2','3'});
        List<ByteBuffer> list=new ArrayList<ByteBuffer>();
        list.add(buffer1);
        list.add(buffer2);
        list.add(buffer3);
        
        ByteBuffer[] byteBufferArray=new ByteBuffer[list.size()];
        list.toArray(byteBufferArray);
        System.out.println(byteBufferArray.length);
        for(int i=0;i<byteBufferArray.length;i++){
            ByteBuffer eachByteBuffer=byteBufferArray[i];
            while (eachByteBuffer.hasRemaining()) {
                System.out.print((char) eachByteBuffer.get());
            }
            System.out.println();
        }
相關文章
相關標籤/搜索