在Java NIO中如果一個channel是FileChannel類型的,那麼他可以直接把資料傳輸到另一個channel。這個特性得益于FileChannel包含的transferTo和transferFrom兩個方法。
transferFrom()
FileChannel.transferFrom方法把資料從通道源傳輸到FileChannel:
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();
toChannel.transferFrom(fromChannel, position, count);
transferFrom的參數position和count表示目标檔案的寫入位置和最多寫入的資料量。如果通道源的資料小于count那麼就傳實際有的資料量。 另外,有些SocketChannel的實作在傳輸時隻會傳輸那些處于就緒狀态的資料,即使SocketChannel後續會有更多可用資料。是以,這個傳輸過程可能不會傳輸整個的資料。
transferTo()
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();
fromChannel.transferTo(position, count, toChannel);