JAVA-4NIO之Channel之間的數據傳輸

轉載:自併發編程網ifeve.com編程

在Java NIO中,若是兩個通道中有一個是FileChannel,那你能夠直接將數據從一個channel(譯者注:channel中文常譯做通道)傳輸到另一個channel。併發

transferFrom():被動接收dom

FileChannel的transferFrom()方法能夠將數據從源通道傳輸到FileChannel中(譯者注:這個方法在JDK文檔中的解釋爲將字節從給定的可讀取字節通道傳輸到此通道的文件中)。socket

方法的輸入參數position表示從position處開始向目標文件寫入數據,count表示最多傳輸的字節數。若是源通道的剩餘空間小於 count 個字節,則所傳輸的字節數要小於請求的字節數。
此外要注意,在SoketChannel的實現中,SocketChannel只會傳輸此刻準備好的數據(可能不足count字節)。所以,SocketChannel可能不會將請求的全部數據(count個字節)所有傳輸到FileChannel中。spa

transferTo():主動發送code

transferTo()方法將數據從FileChannel傳輸到其餘的channel中。下面是一個簡單的例子:對象

除了調用方法的FileChannel對象不同外,其餘的都同樣。
上面所說的關於SocketChannel的問題在transferTo()方法中一樣存在。SocketChannel會一直傳輸數據直到目標buffer被填滿blog

例子:文檔

@Test
    public void test2() {
        RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
        FileChannel fromChannel = fromFile.getChannel();
        RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
        FileChannel toChannel = toFile.getChannel();
        long position = 0;
        long count = fromChannel.size();

        //從from 讀到 本通道;注意socketfrom只會發送已經準備好的,不會發送count個
        toChannel.transferFrom(fromChannel,position, count);
        //將本通道 寫到 to;注意sockedfrom會一直髮送,直到to被填滿
        fromChannel.transferTo(position, count, toChannel);
    }
相關文章
相關標籤/搜索