[java][nio]nio文件拷贝


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 
 * 使用Channel和Buffer拷贝文件
 *
 */
public class ChannelCopy {
	
	private static final int BSIZE = 1024;
	
	public static void main(String[] args) throws Exception {
		channelCopy("d:\\a.txt","d:\\b.txt");
	}
	
	static void channelCopy(String src, String dest) throws Exception{
		//一个输入通道,一个输出通道
		FileChannel in = new FileInputStream(src).getChannel(),
		            out = new FileOutputStream(new File(dest).getAbsoluteFile(),true).getChannel();
		
		ByteBuffer bb = ByteBuffer.allocate(BSIZE);
		while(in.read(bb)!=-1){
			bb.flip();
			out.write(bb);
			bb.clear();
		}
		in.close();
		out.close();
	}
}





import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
/**
 * 
 * 使用transferTo和transferFrom将一个通道和另一个通道相连
 *
 */
public class TransferTo {

	public static void main(String[] args) throws Exception {
		transferTo("d:\\a.txt","d:\\b.txt");
	}
	
	static void transferTo(String src, String dest) throws Exception{
		//一个输入通道,一个输出通道
		FileChannel in = new FileInputStream(src).getChannel(),
		            out = new FileOutputStream(new File(dest).getAbsoluteFile(),true).getChannel();
		
		in.transferTo(0, in.size(), out);//将in通道数据转入out通道,在文件尾
		//out.transferFrom(in, 0, in.size());//将in通道数据转入out通道,会覆盖
		in.close();
		out.close();
	}

}


你可能感兴趣的:(java)