Java NIO系列教程(五) 通道之间的数据传输
在Java NIO中,如果兩個(gè)通道中有一個(gè)是FileChannel,那你可以直接將數(shù)據(jù)從一個(gè)channel(譯者注:channel中文常譯作通道)傳輸?shù)搅硗庖粋€(gè)channel。
transferFrom()
FileChannel的transferFrom()方法可以將數(shù)據(jù)從源通道傳輸?shù)紽ileChannel中(譯者注:這個(gè)方法在JDK文檔中的解釋為將字節(jié)從給定的可讀取字節(jié)通道傳輸?shù)酱送ǖ赖奈募?#xff09;。下面是一個(gè)簡(jiǎn)單的例子:
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 個(gè)字節(jié),則所傳輸?shù)淖止?jié)數(shù)要小于請(qǐng)求的字節(jié)數(shù)。
此外要注意,在SoketChannel的實(shí)現(xiàn)中,SocketChannel只會(huì)傳輸此刻準(zhǔn)備好的數(shù)據(jù)(可能不足count字節(jié))。因此,SocketChannel可能不會(huì)將請(qǐng)求的所有數(shù)據(jù)(count個(gè)字節(jié))全部傳輸?shù)紽ileChannel中。
transferTo()
transferTo()方法將數(shù)據(jù)從FileChannel傳輸?shù)狡渌腸hannel中。下面是一個(gè)簡(jiǎn)單的例子:
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)這個(gè)例子和前面那個(gè)例子特別相似?除了調(diào)用方法的FileChannel對(duì)象不一樣外,其他的都一樣。
上面所說(shuō)的關(guān)于SocketChannel的問(wèn)題在transferTo()方法中同樣存在。SocketChannel會(huì)一直傳輸數(shù)據(jù)直到目標(biāo)buffer被填滿。
原創(chuàng)文章,轉(zhuǎn)載請(qǐng)注明:?轉(zhuǎn)載自并發(fā)編程網(wǎng) – ifeve.com本文鏈接地址:?Java NIO系列教程(五) 通道之間的數(shù)據(jù)傳輸
轉(zhuǎn)載于:https://www.cnblogs.com/lukelook/p/11194933.html
總結(jié)
以上是生活随笔為你收集整理的Java NIO系列教程(五) 通道之间的数据传输的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: axios捕获401 赋值token
- 下一篇: 十大最急需IT技术人才榜:Java开发人