Java NIO 通道之間的數(shù)據(jù)傳輸
在Java NIO中渊啰,如果兩個(gè)通道中有一個(gè)是FileChannel爷耀,那你可以直接將數(shù)據(jù)從一個(gè)channel 傳輸?shù)搅硗庖粋€(gè)channel。
transferFrom()
FileChannel的transferFrom()方法可以將數(shù)據(jù)從源通道傳輸?shù)紽ileChannel中
下面的代碼實(shí)現(xiàn)文件的復(fù)制
package com.viashare.channel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
/**
* Created by Jeffy on 16/5/17.
*/
public class ChannelMain {
private static final String PATH_FROM = "/Users/jeffy-pc/Downloads/test.txt";
private static final String PATH_TO = "/Users/jeffy-pc/Downloads/test3.txt";
public static void main(String[] args) throws IOException {
copy();
}
private static final void copy() throws IOException {
FileInputStream randomAccessFileFrom = new FileInputStream(new File(PATH_FROM));
FileOutputStream randomAccessFileTo = new FileOutputStream(new File(PATH_TO));
FileChannel fromchannel = randomAccessFileFrom.getChannel();
FileChannel tochannel = randomAccessFileTo.getChannel();
long position = 0;
long count = fromchannel.size();
tochannel.transferFrom(fromchannel,position, count);
}
}
方法的輸入?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()
是不是發(fā)現(xiàn)這個(gè)例子和前面那個(gè)例子特別相似契吉?除了調(diào)用方法的FileChannel對(duì)象不一樣外,其他的都一樣诡渴。
上面所說的關(guān)于SocketChannel的問題在transferTo()方法中同樣存在捐晶。SocketChannel會(huì)一直傳輸數(shù)據(jù)直到目標(biāo)buffer被填滿。
private static final void transferToCopy() throws IOException {
FileInputStream randomAccessFileFrom = new FileInputStream(new File(PATH_FROM));
FileOutputStream randomAccessFileTo = new FileOutputStream(new File(PATH_TO));
FileChannel fromchannel = randomAccessFileFrom.getChannel();
FileChannel tochannel = randomAccessFileTo.getChannel();
long position = 0;
long count = fromchannel.size();
fromchannel.transferTo(position, count,tochannel);
}