JAVA NIO之FileChannel

使用通道实现文件复制

package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
 * 通过通道实现文件的复制,通道的操作都是基于BUFFER的,所以速度相对较快
 * 通道是双向的的既可以读也可以写
 *
 */
public class FileChannelTest {


	public static void main(String[] args) throws Exception{
		//打开文件
		File source = new File("e:"+File.separator+"abc.txt");
		File target = new File("e:"+File.separator+"xyz.txt");
		//构建流
		FileInputStream fis = new FileInputStream(source);
		FileOutputStream fos = new FileOutputStream(target);
		//获得通道
		FileChannel cin = fis.getChannel();
		FileChannel cout = fos.getChannel();
		//循环使用通道读写缓冲区,实现文件复制
		ByteBuffer buf = ByteBuffer.allocate(10);
		while(cin.read(buf) != -1){
			buf.flip();
			cout.write(buf);
			buf.clear();
		}
		//关闭操作
		cin.close();cout.close();
		fis.close();fos.close();		
	}


}



你可能感兴趣的:(JAVA NIO之FileChannel)