文件的拷贝

<div yne-bulb-block="paragraph" style="white-space: pre-wrap;"><span style="font-family:Arial;"><span style="font-size: 13px; line-height: 19.5px;">带缓冲的作用:</span></span></div><div yne-bulb-block="paragraph" style="white-space: pre-wrap; line-height: 1.5; font-size: 14px;"><span style="font-size: 13px; font-family: Arial;"><span style="white-space:pre">	</span>不带缓冲的操作,每读一个字节就要写入一个字节,由于涉及磁盘的IO操作相比内存的操作要慢很多,所以不带缓冲的流效率很低。带缓冲的流,可以一次读很多字节,但不向磁盘中写入,只是先放到内存里。等凑够了缓冲区大小的时候一次性写入磁盘,这种方式可以减少磁盘操作次数,但是内存会占用的多,速度就会提高很多!</span></div>

<pre name="code" class="java">import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileUtils {
	/*
	 * srcFile 源文件 
	 * destFile 目标文件
	 *  num 定制缓冲数组大小(单位KB)
	 */

	public static void copyFile(File srcFile, File destFile, int num) {

		if (!srcFile.exists()) {
			throw new IllegalArgumentException(srcFile + "不存在");
		}
		if (!srcFile.isFile()) {
			throw new IllegalArgumentException(srcFile + "不是文件");
		}

		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		byte[] buf = new byte[num * 1024];
		int len = 0;

		try {
			bis = new BufferedInputStream(new FileInputStream(srcFile));
			bos = new BufferedOutputStream(new FileOutputStream(destFile));
			while ((len = bis.read(buf, 0, buf.length)) != -1) {
				bos.write(buf, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bis.close();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void copyTextFile(File srcFile, File destFile, int num) {

		BufferedReader br = null;
		BufferedWriter bw = null;
		char[] cbuf = new char[num * 1024];
		int len = 0;

		try {
			br = new BufferedReader(new FileReader(srcFile));
			bw = new BufferedWriter(new FileWriter(destFile));
			while ((len = br.read(cbuf, 0, cbuf.length)) != -1) {
				bw.write(cbuf, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}


 

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值