1. 程式人生 > >NIO buffer和channel

NIO buffer和channel

1:buffer類沒有提供構造器,通過如下的方法來得到一個Buffer物件:static XxxBuffer allocate(int capcacity)

2:所有的Channel都不應該通過構造器來直接建立,而是通過傳統的節點InputStream、OutputStream等的getChannel()方法來返回對應的Channel,不同的節點流獲得的Channel不一樣。程式不能直接和訪問Channel中的資料,包括讀取、寫入都不行,Channel只能與Buffer進行互動。也就是說,如果要從Channel中獲取資料,必須首先將Channel中的一些資料read到Buffer中,然後讓程式從Buffer中get出這些資料;

如果將程式中的資料寫入Channel,一樣先讓程式將資料put入Buffer中,程式再將Buffer裡的資料寫入Channel中。

public static void method1(){
        RandomAccessFile aFile = null;
        try{
            aFile = new RandomAccessFile("src/nio.txt","rw");
            FileChannel fileChannel = aFile.getChannel();
            ByteBuffer buf = ByteBuffer.allocate(1024);
            int bytesRead = fileChannel.read(buf);
            System.out.println(bytesRead);
            while(bytesRead != -1)
            {
                buf.flip();
                while(buf.hasRemaining())
                {
                    System.out.print((char)buf.get());
                }
                buf.compact();
                bytesRead = fileChannel.read(buf);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            try{
                if(aFile != null){
                    aFile.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }