在java NIO中光涂,你可以直接在channel和channel之間傳輸數(shù)據(jù)齐唆。如果其中一個(gè)是FileChanel的話律秃,F(xiàn)ileChanel類為你提供的有一個(gè)transferTo()和transferFrom()方法呈昔。
一、transferFrom()
FileChannel.transferFrom()方法會(huì)把一個(gè)源channel中的數(shù)據(jù)傳輸?shù)揭粋€(gè)FileChannel中友绝,下面是一個(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(fromChannel, position, count);
position和count參數(shù)就是告訴你從目標(biāo)文件的哪里處開(kāi)始寫入(position),以及最大傳輸多少字節(jié)的數(shù)據(jù)堤尾。如果源channel中的數(shù)據(jù)比count要少的話,那么只會(huì)傳輸很少的一部分迁客。
另外郭宝,一些SocketChannel實(shí)現(xiàn)只會(huì)傳輸在此時(shí)此刻它的內(nèi)部緩沖區(qū)中已準(zhǔn)備好的數(shù)據(jù)--即使該SocketChannel之后有了更多可用的數(shù)據(jù)。因此掷漱,它不會(huì)把請(qǐng)求的全部數(shù)據(jù)(count)傳輸?shù)揭粋€(gè)FileChannel中粘室。
二、transferTo()
transferTo()方法會(huì)把FileChannel中的數(shù)據(jù)傳輸?shù)狡渌恍ヽhannel中卜范,這里有一些簡(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);
注意一下:這個(gè)例子和原來(lái)的有多么相像衔统。真正的不同之處是調(diào)用的是哪一個(gè)FileChannel對(duì)象的方法。其余的都是相同的海雪。SocketChannel的實(shí)現(xiàn)僅僅當(dāng)發(fā)送緩沖區(qū)滿了的時(shí)候才會(huì)傳輸FileChannel中的字節(jié)然后再停止锦爵。