參考:http://ifeve.com/java-nio-channel-to-channel/
原文地址
目錄
- Java NIO教程
- Java NIO 教程(一) 概述
- Java NIO 教程(二) Channel
- Java NIO 教程(三) Buffer
- Java NIO 教程(四) Scatter/Gather
- Java NIO 教程(五) 通道之間的數(shù)據(jù)傳輸
- Java NIO 教程(六) Selector
- Java NIO 教程(七) FileChannel
- Java NIO 教程(八) SocketChannel
- Java NIO 教程(九) ServerSocketChannel
- Java NIO 教程(十) 非阻塞式服務(wù)器
- Java NIO 教程(十一) Java NIO DatagramChannel
- Java NIO 教程(十二) Pipe
- Java NIO 教程(十三) Java NIO vs. IO
- Java NIO 教程(十四) Java NIO Path
- Java NIO 教程(十五) Java NIO Files
- Java NIO 教程(十六) Java NIO AsynchronousFileChannel
在Java NIO中,如果兩個通道中有一個是FileChannel
,那你可以直接將數(shù)據(jù)從一個channel
(譯者注:channel中文常譯作通道)傳輸?shù)搅硗庖粋€channel
。
transferFrom()
FileChannel
的transferFrom()
方法可以將數(shù)據(jù)從源通道傳輸?shù)?code>FileChannel中(譯者注:這個方法在JDK文檔中的解釋為將字節(jié)從給定的可讀取字節(jié)通道傳輸?shù)酱送ǖ赖奈募校O旅媸且粋€簡單的例子:
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(position, count, fromChannel);
方法的輸入?yún)?shù)position
表示從position
處開始向目標(biāo)文件寫入數(shù)據(jù),count
表示最多傳輸?shù)淖止?jié)數(shù)。如果源通道的剩余空間小于 count
個字節(jié),則所傳輸?shù)淖止?jié)數(shù)要小于請求的字節(jié)數(shù)。
此外要注意,在SoketChannel
的實現(xiàn)中,SocketChannel
只會傳輸此刻準(zhǔn)備好的數(shù)據(jù)(可能不足count
字節(jié))。因此,SocketChannel
可能不會將請求的所有數(shù)據(jù)(count
個字節(jié))全部傳輸?shù)?code>FileChannel中。
transferTo()
transferTo()
方法將數(shù)據(jù)從FileChannel
傳輸?shù)狡渌?code>channel中。下面是一個簡單的例子:
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);
是不是發(fā)現(xiàn)這個例子和前面那個例子特別相似?除了調(diào)用方法的FileChannel
對象不一樣外,其他的都一樣。
上面所說的關(guān)于SocketChannel
的問題在transferTo()
方法中同樣存在。SocketChannel
會一直傳輸數(shù)據(jù)直到目標(biāo)buffer
被填滿。