NIO(2) Channel之間數據傳輸

      Java NIO中,如果兩個通道中有一個是FileChannel,可以直接將數據從一個channel傳輸到另外一個channel。

  • transferFrom
    FileChannel的transferFrom()方法可以將數據從源通道傳輸到FileChannel中
    public void testTransferFrom() throws Exception {
        RandomAccessFile srcraf = new RandomAccessFile(
                new File("D:/downloads/task.ini"), "rw");
        FileChannel srcChannel = srcraf.getChannel();

        RandomAccessFile destraf = new RandomAccessFile(
                new File("D:/downloads/task2.ini"), "rw");
        FileChannel destChannel = destraf.getChannel();

        destChannel.transferFrom(destChannel, 0, srcChannel.size());

        srcraf.close();
        destraf.close();
    }
  • transferTo
    ransferTo()方法將數據從FileChannel傳輸到其他的channel中
    public void testTransferFrom() throws Exception {
        RandomAccessFile srcraf = new RandomAccessFile(
                new File("D:/360Downloads/task.ini"), "rw");
        FileChannel srcChannel = srcraf.getChannel();

        RandomAccessFile destraf = new RandomAccessFile(
                new File("D:/360Downloads/task2.ini"), "rw");
        FileChannel destChannel = destraf.getChannel();

        srcChannel.transferTo(0, srcChannel.size(), destChannel);

        srcraf.close();
        destraf.close();
    }

注:以上兩個方法中在SoketChannel的實現中,SocketChannel只會傳輸此刻準備好的數據(可能不足count字節)。因此,SocketChannel可能不會將請求的所有數據(count個字節)全部傳輸到FileChannel中

發佈了59 篇原創文章 · 獲贊 7 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章