JAVA IO和NIO复制文件_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > JAVA IO和NIO复制文件

JAVA IO和NIO复制文件

 2013/10/10 18:30:15  dreamoftch  程序员俱乐部  我要评论(0)
  • 摘要:packagecom.tch.test.t1;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.nio.ByteBuffer;importjava.nio.channels.FileChannel;publicclassFileCopyUtils{/***Createdon2013-10-10*<p>*Discription:*</p>**@author
  • 标签:文件 Java 复制

?

?

class="java">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);
	}

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

?

发表评论
用户名: 匿名