Java NIO總結

NIO是Java 1.4開始引入的,目的是替代標準IO,它采用了與標準IO完全不同的設計模式和工作方式,這里就來總結一下。

1.Buffer

正如他的名字,就是一個緩存,實際上是內存的一塊區域,它是NIO體系的重要組成部分,主要和通道進行交互。 Buffer本身是一個抽象類,它有以下幾個子類:
ByteBuffer
CharBuffer
DoubleBuffer
FloatBuffer
IntBuffer
LongBuffer
ShortBuffer
根據緩存的數據類型不同創建的不同子類,大致功能都類似,我們不一個一個介紹,只介紹Buffer的關鍵點。

Buffer的使用一般如下:將數據寫入buffer,準備從buffer中讀數據,讀取數據,清空buffer。下面先簡單演示一下然后再解釋:

    public static void main(String[] args) throws IOException {
        try (RandomAccessFile file = new RandomAccessFile("file/test.txt","rw");
             FileChannel channel = file.getChannel()){
            ByteBuffer buffer = ByteBuffer.allocate(5);
            int len;
            while((len = channel.read(buffer))!=-1){
                buffer.flip();
                while (buffer.hasRemaining())
                    System.out.println((char)buffer.get());
                buffer.compact();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

先看構造,Buffer的子類也都是抽象類,不能直接實例化,都需要調用靜態方法生成,可以看源碼,調用不同的靜態方法實例化不同的實現類。以ByteBuffer為例,可以這樣實例化:

allocate(int capacity) //分配一個大小為capacity的字節數組作為緩沖,但是在堆中
allocateDirect(int capacity) //和上面類似,不過直接借助系統在內存中創建,速度較快,但消耗性能
wrap(byte[] array) //直接從外部指定一個數組,不適用默認創建的,但是雙方一方改動就會影響另一方
wrap(byte[] array, int offset, int length) //和上面一個一樣,但是能指定偏移量和長度

我們獲得一個Buffer實例后就可以使用,首先向buffer中寫東西需要channel配合,調用read方法即可。之后在讀之前需要準備一下,從代碼看就是調用flip方法,這個方法有什么作用呢?從文檔上看,就是將limit設置為position,然后將position 置零。這樣有什么用呢?下面就來介紹一下buffer的幾個成員變量:capacity,limit,position。

capacity就是一個buffer的固定大小,表示他的容量
position表示當前指針的位置,也就是當前讀或寫到的位置
limit這個值在寫模式下表示最多能寫多少,寫模式下等于capacity。讀模式下表示能讀到多少,調用flip將limit等于position,表示最多能讀到之前寫入的所有內容

看flip的實現也很好理解,如下:

    public final Buffer flip() {
        limit = position;
        position = 0;
        mark = -1;
        return this;
    }

剛才是準備讀數據,下面就是從中讀了,buffer有一系列get方法,和流的read方法類似。既然有get就有put方法,除了上面和channel配合寫入東西,還可以用一系列put方法寫入。讀之前可以判斷一下是否還有數據:hasRemaining();讀完之后為了使下次還能用,需要清空buffer,可以用clear方法或者compact方法??梢钥匆幌滤麄兊膶崿F:

    public final Buffer clear() {
        position = 0;
        limit = capacity;
        mark = -1;
        return this;
    }
    public ByteBuffer compact() {
        System.arraycopy(hb, ix(position()), hb, ix(0), remaining());
        position(remaining());
        limit(capacity());
        discardMark();
        return this;
    }

clear方法很清晰,就是將幾個游標歸為為原始狀態。compact也是設置幾個游標位置,不過有點特殊,remaining方法是獲取剩余數據數量就是limit - position,然后將該值賦給position,然后將capacity賦值給limit。他和clear的區別就是在position上的處理。但是,如果我們已經將buffer內容讀完,這時limit = position,那么 position(remaining())的效果就是position = limit - position = 0.這時compact方法效果等于clear。否則雖然也可以繼續寫內容進去,但容量減少,但好處是未讀的數據以后可以繼續讀。

再來看其他方法:

    public final Buffer rewind() {
        position = 0;
        mark = -1;
        return this;
    }

rewind是將position 置零,也就是buffer中內容可以重新讀取。

    public final Buffer mark() {
        mark = position;
        return this;
    }
    public final Buffer reset() {
        int m = mark;
        if (m < 0)
            throw new InvalidMarkException();
        position = m;
        return this;
    }

mark和reset是配合使用的。mark標記一個位置,reset使游標回到這個位置。mark成員變量初始為-1.所以不要沒有調用mark方法就去調用reset。

可以看到buffer的主要操作就是針對幾個指針的,畢竟他是依賴于數組實現的。

2.Channel

Channel用來實現通道的概念,他類似于流,但是不能直接操作數據,需要借助于Buffer,它本身是一個接口,一般有以下幾個重要實現:
FileChannel
DatagramChannel
SocketChannel
ServerSocketChannel

2.1 FileChannel

FileChannel是一個用于讀寫操作文件的channel。首先看怎么獲得實例化對象,FileChannel也是一個抽象類,所以不能通過構造獲得。一般獲得的途徑有,RandomAccessFile、FileOutputStream、FileInputStream等一些類的getChannel()方法,如上文中示例。

另外在Java 1.7 中提供了幾個靜態的open方法用來直接打開或創建文件獲取Channel:

    public static void main(String[] args) throws IOException {
        try (FileChannel channel = FileChannel.open(Paths.get("file/test.txt"), StandardOpenOption.READ)){
            ByteBuffer buffer = ByteBuffer.allocate(5);
            int len;
            while((len = channel.read(buffer))!=-1){
                buffer.flip();
                while (buffer.hasRemaining())
                    System.out.println((char)buffer.get());
                buffer.compact();
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

Channel是不能直接讀數據的,需要借助于buffer,同樣寫內容也是要借助于buffer,下面演示一下傳統的復制文件。

    public static void main(String[] args) throws IOException {
        try (FileChannel readChannel = FileChannel.open(Paths.get("file/test.png"), StandardOpenOption.READ)){
            FileChannel writeChannel = FileChannel.open(Paths.get("file/copy.png"), StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE);
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (readChannel.read(buffer)!=-1){
                buffer.flip();
                while (buffer.hasRemaining())
                    writeChannel.write(buffer);
                buffer.clear();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

有一點需要注意的是,有時并不能保證把整個buffer的內容寫入,為了嚴謹起見,需要循環判斷buffer中是否有內容未寫入。

除了上面傳統的寫法,channel還有自己特有的傳輸方法:

        try (FileChannel readChannel = FileChannel.open(Paths.get("file/test.png"), StandardOpenOption.READ)){
            FileChannel writeChannel = FileChannel.open(Paths.get("file/copy.png"), StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE);
            //以下兩句話效果一樣
            //writeChannel.transferFrom(readChannel,0,readChannel.size());
            readChannel.transferTo(0,readChannel.size(),writeChannel);
        }catch (Exception e){
            e.printStackTrace();
        }

transferFrom和transferTo都是把一個channel的內容傳輸到另一個,但是注意兩個方法的區別,即方向性。

上面示例用到了size()方法,是用來獲取所關聯文件的大小。

position()和position(long)方法用來獲取指針位置和設置指針位置。設置position是可以將指針設置到文件結束符之后的,但是中間會有空洞。

truncate(long)方法可一截取一個文件并返回FileChannel,從文件開始截取到指定位置。

2.2 DatagramChannel

DatagramChannel是Java UDP通信中傳輸數據的通道。關于Java中傳統UDP的實現見這里,下面簡單用DatagramChannel實現一下UDP通信
服務端

public class UDPService {
    public static final String SERVICE_IP = "127.0.0.1";

    public static final int SERVICE_PORT = 10101;

    public static void main(String[] args) {
        UDPService service = new UDPService();
        service.startService(SERVICE_IP,SERVICE_PORT);
    }

    private void startService(String ip, int port){
        try (DatagramChannel channel = DatagramChannel.open()){
            channel.bind(new InetSocketAddress(ip,port));
            while (true){
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                SocketAddress socketAddress = channel.receive(buffer);
                String receive = new String(buffer.array(),"UTF-8").trim();
                System.out.println("address: " + socketAddress.toString()+ " msg: "+ receive);
                buffer.clear();
                buffer.put((receive + "hello world").getBytes());
                buffer.flip();
                channel.send(buffer,socketAddress);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

客戶端

public class UDPClient {

    public static void main(String[] args){
        UDPClient client = new UDPClient();
        Scanner scanner = new Scanner(System.in);
        while(true){
            String msg = scanner.nextLine();
            if("##".equals(msg))
                break;
            System.out.println(client.sendAndReceive(UDPService.SERVICE_IP,UDPService.SERVICE_PORT,msg));
        }
    }

    private String sendAndReceive(String serviceIp, int servicePort, String msg) {
        try (DatagramChannel channel = DatagramChannel.open()){
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            buffer.put(msg.getBytes());
            System.out.println(buffer.position());
            buffer.flip();
            SocketAddress address = new InetSocketAddress(serviceIp,servicePort);
            System.out.println( channel.send(buffer,address));
            buffer.clear();
            SocketAddress socketAddress = channel.receive(buffer);
            return "address: " + socketAddress.toString()+ " msg: "+ new String(buffer.array(),"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "null";
    }
}

一般獲得一個DatagramChannel 需要使用靜態方法open,DatagramChannel 也是配合buffer使用的。之后服務端需要綁定一個地址和端口。接下來就可以收發數據了,收用receive方法,返回發送方的地址信息,發生使用send方法,返回成功發生的字節數。

有一點特別重要,由于是配合buffer操作,無論是客戶端還是服務端,在發送前都需要調用flip方法,否則發送的都是空數據(因為都是從position到limit,flip之前position是當前寫的位置,limit為capacity)。還有一點,在接受時,由于不知道buffer中有效字節數,所以limit為capacity,直觀的看就是轉為字符串時末尾有大量空內容,需要trim一下。

默認情況下是阻塞的,也可以設置為非阻塞的,channel.configureBlocking(true);,此時receive方法會立刻返回,可能為null。channel也有connect方法,但是UDP是非連接的,所以只是綁定一個遠端地址,收發智能從指定地址來。connect之后就可以用read或者write收發數據。

2.3 SocketChannel 與 ServerSocketChannel

這兩類是和Socket與 ServerSocket對應的兩個雷,也是專為TCP通信設計的,ServerSocketChannel代表服務端,SocketChannel 代表一個連接。關于Java的傳統TCP實現見這里,下面簡單實現一下TCP通信
服務端:

public class TCPService {
    public static final String SERVICE_IP = "127.0.0.1";

    public static final int SERVICE_PORT = 10101;

    public static void main(String[] args) {
        TCPService service = new TCPService();
        service.startService();
    }
    private void startService(){
        try (ServerSocketChannel service = ServerSocketChannel.open()){
            service.bind(new InetSocketAddress(SERVICE_IP,SERVICE_PORT));
            while (true){
                SocketChannel channel = service.accept();
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                StringBuilder msg = new StringBuilder();
                while ((len = channel.read(buffer)) > 0) {
                    receive.append(new String(buffer.array(), 0, len));
                    buffer.clear();
                }
                System.out.println("address: " + channel.getRemoteAddress().toString() + " msg: " + msg.toString());

                buffer.clear();
                buffer.put((msg + "hello world").getBytes());
                buffer.flip();
                while (buffer.hasRemaining())
                    channel.write(buffer);
                channel.shutdownOutput();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

客戶端

public class TCPClient {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        TCPClient client = new TCPClient();
        while(true){
            System.out.println(client.sendAndReceive(TCPService.SERVICE_IP,TCPService.SERVICE_PORT,scanner.nextLine()));
        }
    }

    private String sendAndReceive(String address,int port,String msg){
        try (SocketChannel channel = SocketChannel.open()){
            channel.connect(new InetSocketAddress(address,port));
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            buffer.put(msg.getBytes());
            buffer.flip();
            while (buffer.hasRemaining())
                channel.write(buffer);
            channel.shutdownOutput();
            buffer.clear();

            StringBuilder receive = new StringBuilder();
            int len = 0;
            while ((len = channel.read(buffer)) > 0) {
                receive.append(new String(buffer.array(), 0, len));
                buffer.clear();
            }
            return "address: " + channel.getRemoteAddress().toString() + " msg: " + receive.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return "null";
    }
}

同樣都是利用open獲取一個示例,服務端要綁定地址和端口,然后監聽連接,客戶端只需去連接服務端即可。同樣的都可以設置為非阻塞的,收發數據使用read和write方法。需要注意的還是buffer操作問題以及即使關流或者做控制就行。

3.Selector

Selector 可以同時監控多個Channel 的 IO 狀況,也就是說,利用 Selector可使一個單獨的線程管理多個 Channel,selector 是非阻塞 IO 的核心。簡單示例
客戶端

public class TCPClient {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        TCPClient client = new TCPClient();
        while(true){
            client.sendAndReceive(TCPService.SERVICE_IP,TCPService.SERVICE_PORT,scanner.nextLine());
        }
    }

    private void sendAndReceive(String address,int port,String msg){
        try (SocketChannel channel = SocketChannel.open()){
            channel.connect(new InetSocketAddress(address, port));
            ByteBuffer buf = ByteBuffer.allocate(1024);
            channel.configureBlocking(false);
            buf.put((new Date() + ":" + msg).getBytes());
            buf.flip();
            channel.write(buf);
            buf.clear();
            channel.shutdownOutput();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

服務端

public class TCPService {
    public static final String SERVICE_IP = "127.0.0.1";

    public static final int SERVICE_PORT = 10101;

    private String msg;

    public static void main(String[] args) {
        TCPService service = new TCPService();
        service.startService();
    }
    private void startService(){
        try (ServerSocketChannel service = ServerSocketChannel.open()){
            service.bind(new InetSocketAddress(SERVICE_IP,SERVICE_PORT));
            service.configureBlocking(false);
            Selector selector = Selector.open();
            service.register(selector, SelectionKey.OP_ACCEPT);
            while (selector.select() > 0) {
                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                while (it.hasNext()) {
                    SelectionKey key = it.next();
                    if (key.isAcceptable()) {
                        System.out.println("isAcceptable");
                        SocketChannel sc = service.accept();
                        sc.configureBlocking(false);
                        sc.register(selector, SelectionKey.OP_READ );
                    } else if (key.isReadable()) {
                        System.out.println("isReadable");
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buf = ByteBuffer.allocate(1024);
                        int len = 0;
                        StringBuilder sb = new StringBuilder();
                        while ((len = channel.read(buf)) > 0) {
                            sb.append(new String(buf.array(), 0, len));
                            buf.clear();
                        }
                        System.out.println(sb.toString());
                        channel.close();
                    }
                    it.remove();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

主要是服務端的應用,基本流程就是先利用open()方法獲取一個Selector ,設置ServerSocketChannel 為非阻塞的,之后注冊事件,一般有以下幾種

SelectionKey.OP_CONNECT
SelectionKey.OP_ACCEPT
SelectionKey.OP_READ
SelectionKey.OP_WRITE

之后調用select()返回就緒通道數,然后根據時間類型執行具體操作即可。

4.Pipe

傳統IO為我們提供了線程間通信的類,PipedInputStream與PipedOutputStream。NIO作為IO的替代者,自然也有線程通信的方法,就是Pipe,使用起來很簡單,如下:

public class Receiver extends Thread{
    private Pipe pipe;

    public void setPipe(Pipe pipe){
        this.pipe = pipe;
    }
    @Override
    public void run() {
        super.run();
        try (Pipe.SourceChannel channel = pipe.source()){
            ByteBuffer buf = ByteBuffer.allocate(1024);
            int len = 0;
            StringBuilder sb = new StringBuilder();
            while((len = channel.read(buf))!=-1){
                sb.append(new String(buf.array(),0,len));
                buf.clear();
            }
            System.out.println(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
public class Sender extends Thread{
    private Pipe pipe;

    public void setPipe(Pipe pipe){
        this.pipe = pipe;
    }
    @Override
    public void run() {
        super.run();
        try (Pipe.SinkChannel channel = pipe.sink()){
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            buffer.put("hello world".getBytes());
            buffer.flip();
            while (buffer.hasRemaining())
                channel.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
    public static void main(String[] args) throws IOException {
        Receiver receiver = new Receiver();
        Sender sender = new Sender();
        Pipe pipe = Pipe.open();
        receiver.setPipe(pipe);
        sender.setPipe(pipe);
        receiver.start();
        sender.start();
    }

Pipe只是一個管理者,收發數據還是通過兩個通道:SinkChannel 和SourceChannel 。都是單項的,SinkChannel 負責寫數據,SourceChannel 負責收數據。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容