首次獨立完成文件拷貝操作,【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;

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 {
			input = new FileInputStream(inFile);
			output = new FileOutputStream(outFile);
			copyHandle(input, output);
			flag = true;
		} catch (Exception e) {
			flag = false;
		} finally {
			try {
				input.close();
				output.close();
			} catch (Exception e) {
			}
		}
		return flag;
	}

	private static void copyHandle(InputStream input, OutputStream output) throws IOException {
		long start = System.currentTimeMillis();
		int temp = 0;
		do {
			temp = input.read();
			output.write(temp);
		} while (temp != -1);
		long end = System.currentTimeMillis();
		System.out.println("【統計】拷貝文件花費時間:" + (end - start));
	}
}

public class Copy {
	public static void main(String args[]) {
		if (args.length != 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("拷貝未完成,源文件路徑不存在!");
		}
	}
}

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