JAVA IO和NIO复制文件

2 篇文章 0 订阅
1 篇文章 0 订阅

 

 

package com.tch.test.t1;

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

public class FileCopyUtils {

	/**
	 * Created on 2013-10-10
	 * <p>
	 * Discription:
	 * </p>
	 * 
	 * @author:
	 * @return void
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		String source = "D:\\Program files\\tomcat6\\temp\\7C-setup.exe";
		String destination = "D:\\Program files\\tomcat6\\temp\\setup.exe";
		String destination2 = "D:\\Program files\\tomcat6\\temp\\setup2.exe";
		copyByNIO(source, destination);
		copyByIO(source, destination2);
	}
        //NIO 复制文件
	public static void copyByNIO(String source,String destination) throws Exception {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		FileChannel fci = null;
		FileChannel fco = null;
		try {
			//打开stream
			fis = new FileInputStream(source);
			fos = new FileOutputStream(destination);
			//打开channel
			fci = fis.getChannel();
			fco = fos.getChannel();
			//buffer对象
			ByteBuffer buffer = ByteBuffer.allocate(10240);
			//开始复制
			while (true) {
				int n = fci.read(buffer);
				if (n == -1) break; //说明复制完成
				buffer.flip();
				fco.write(buffer);
				buffer.clear();
			}
		} catch (Exception e) {
			throw e;
		}finally{
			if(fis != null){
				fis.close();
				fis = null;
			}
			if(fos != null){
				fos.flush();
				fos.close();
				fos = null;
			}
			if(fci != null){
				fci.close();
				fci = null;
			}
			if(fco != null){
				fco.close();
				fco = null;
			}
		}
	}
	//IO 复制
	public static void copyByIO(String source,String destination) throws Exception {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			//打开stream
			fis = new FileInputStream(source);
			fos = new FileOutputStream(destination);
			int n = -1;
			byte[] b = new byte[10240];
			while((n=fis.read(b)) != -1){
				fos.write(b, 0, n);
			}
		} catch (Exception e) {
			throw e;
		}finally{
			if(fis != null){
				fis.close();
				fis = null;
			}
			if(fos != null){
				fos.flush();
				fos.close();
				fos = null;
			}
		}
	}
	
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值