JAVA IO和NIO复制文件

 

 

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;
			}
		}
	}
	
	
}

 

你可能感兴趣的:(java,IO,nio,复制文件)