java 文件复制

</pre><pre name="code" class="java">package com.jack.io.bio;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class FileTest {

	private BufferedOutputStream bos;
	private BufferedInputStream bis;
	private FileInputStream fis;
	private FileOutputStream fos;
	private FileChannel fin;
	private FileChannel fout;

	//传统方式  速度慢,效率差,容易出错
	public void copyFile(String srcPath, String tgtPath) {
		try {
			bis = new BufferedInputStream(new FileInputStream(srcPath));
			bos = new BufferedOutputStream(new FileOutputStream(tgtPath));
			int len;
			byte[] buffer = new byte[1024 * 1024];

			while ((len = bis.read(buffer)) != -1) {
				bos.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	//速度快 ,效率高,零拷贝
	//http://www.ibm.com/developerworks/cn/java/j-zerocopy/ 
	public void copyFile2(String srcPath, String tgtPath) {
		long length;
		try {
			fis = new FileInputStream(srcPath);
			fin = fis.getChannel();
			fos = new FileOutputStream(tgtPath);
			fout = fos.getChannel();
			length = fin.size();
			fin.transferTo(0, length, fout);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fin != null) {
				try {
					fin.close();
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (fout != null) {
				try {
					fout.close();
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	//Try-with-resource jdk1.7新特性
	//效率高,简短,不容易出错
	public void copyFileJdk17(String srcPath, String tgtPath) {
		try(FileInputStream fis2 = new FileInputStream(srcPath); 
			FileChannel	 fin2 = fis2.getChannel(); 
			FileOutputStream fos2 = new FileOutputStream(tgtPath); 
			FileChannel fout2 = fos2.getChannel()){ 
			fin2.transferTo(0, fin2.size(), fout2); 
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		FileTest test = new FileTest();
		test.copyFileJdk17("e:\\test.mp4", "e:\\test2.mp4");
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值