文件拷贝操作,优化do while 及拷贝时间

package cn.yhy.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
 * 创建一个单独的类,实现以下方法:
 * 1.判断源文件是否存在;
 * 2.判断目标文件父路径是否存在,不存在则创建;
 * 3.实现复制操作;
 * @author yuhy
 *
 */
class CopyUtil{
	private CopyUtil() {}
	public static boolean fileExists(String path) {	//判断源文件是否存在
		return new File(path).exists();
	}
	public static void creatParentDirectory(String path) {	//创建父路径
		File file = new File(path);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
	}
	public static boolean copy(String srcPath,String desPath) {	//进行拷贝处理
		boolean flag = false;	//拷贝操作标记
		File inFile = new File(srcPath);	//实例化源文件
		File outFile = new File(desPath);	//实例化目标文件
		InputStream input = null;
		OutputStream output = null;
		try {
			//InputStream类是一个抽象类,对文件进行处理使用FileInputStream类完成;
			//OutputStream类是一个抽象类,对文件进行处理使用FileOutputStream类完成;
			input = new FileInputStream(inFile);	//字节输入流
			output = new FileOutputStream(outFile);	//字节输出流
			copyHandle(input,output);	//实际拷贝处理
			flag = true;
		} catch (IOException e) {
			flag = false;
		} finally {
			try {
				input.close();
				output.close();
			} catch (IOException e) {}
		}
		return flag;
	}
	private static void copyHandle(InputStream input,OutputStream output) throws IOException {	// 实际拷贝处理过程
		long start = System.currentTimeMillis();	//获得系统当前时间
		int temp = 0;	
		byte data[] = new byte[1024];	//创建一个字节数组
		while ((temp = input.read(data)) != -1) {	//不是-1,表示还有内容
			output.write(temp);
		}
		long end = System.currentTimeMillis();
		System.out.println("【统计】拷贝共花费时间:" + (end - start) + "毫秒");
	}
}
public class Copy{
	public static void main(String args[]) throws IOException {
		if (args.length != 2) {	//源文件路径及目标文件路径是2个对象
			System.out.println("执行方式错误,请按照java Copy 源文件路径 目标文件路径 进行执行");
			System.exit(1);	//系统退出
		}
		if (CopyUtil.fileExists(args[0])) {	//如果源文件存在,则进行拷贝
			CopyUtil.creatParentDirectory(args[1]);	//创建目标文件路径
			System.out.println(CopyUtil.copy(args[0], args[1]) ? "文件拷贝完成!" : "文件拷贝出现错误!");	//三元表达式
		} else {
			System.out.println("拷贝未能进行,源文件不存在!");
		}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章