`
周一Monday
  • 浏览: 342498 次
  • 来自: 北京
社区版块
存档分类
最新评论

文件复制工具类

 
阅读更多
package io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 文件复制
 * 
 * @author Monday
 */
public class FileCopy {

	/**
	 * 复制文本文件
	 * 
	 * @param src 源文件的目录
	 * @param dest 目标文件的目录
	 */
	public static void copyText(String src, String dest) {
		BufferedReader bufr = null;
		BufferedWriter bufw = null;
		try {
			bufr = new BufferedReader(new FileReader(src));
			bufw = new BufferedWriter(new FileWriter(dest));
			String str = null;
			while ((str = bufr.readLine()) != null) {
				bufw.write(str); // 写入文件
				bufw.newLine(); // 写入换行符
				bufw.flush(); // 刷新缓冲
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bufw != null) {
				try {
					bufw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bufr != null) {
				try {
					bufr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 复制二进制文件 
	 * 例如:图片、音频、视频 
	 * 文本也可以
	 * 
	 * @param src 源文件的目录
	 * @param dest 目标文件的目录
	 */
	public static void copyBinary(String src, String dest) {
		BufferedInputStream bufi = null;
		BufferedOutputStream bufo = null;
		try {
			bufi = new BufferedInputStream(new FileInputStream(src));
			bufo = new BufferedOutputStream(new FileOutputStream(dest));
			int len = 0;
			byte[] b = new byte[bufi.available()];
			while ((len = bufi.read(b)) != -1) {
				bufo.write(b, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bufo != null) {
				try {
					bufo.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bufi != null) {
				try {
					bufi.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 测试
	 */
	public static void main(String[] args) {
		FileCopy.copyText("src/复习计划.txt", "src/复习计划_copy.txt");
		System.out.println("ok");

		System.out.println("============");

		FileCopy.copyBinary("src/numb.mp3", "src/numb_copy.mp3");
		System.out.println("ok");
	}
}

 

上面的代码用了很多Bufered...是为了提高效率。提高效率多写几行代码还是值得的。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics