自己动手实现文件拷贝操作

利用输入输出流实现文件的拷贝操作。将源文件地址与目标地址作为参数传入即可。


package com.example.j8;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

class Util {
	// 构造函数私有
	private Util() {

	}

	public static boolean exists(String str) {
		return new File(str).exists();
	}

	/**
	 * 创建父目录
	 * 
	 * @param str
	 */
	public static void createParentDirectory(String str) {
		File file = new File(str);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}

	}

	public static boolean copyFile(String str, String des) throws Exception {
		boolean flag = false;
		File file = new File(str);
		File fileOut = new File(des);
		InputStream input = null;
		OutputStream output = null;

		try {
			input = new FileInputStream(file);
			output = new FileOutputStream(fileOut);
			copyFileHandler(input, output);
		} catch (Exception e) {
			flag = false;
		} finally {
			try {
				input.close();
				output.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}

		
		flag = true;
		return flag;
	}

	private static void copyFileHandler(InputStream input, OutputStream output) throws Exception {
		long start = System.currentTimeMillis();
		byte data[] = new byte[2048];
		int temp = 0;
		while ((temp = input.read(data)) != -1) {
			output.write(data, 0, temp);
		}
		long end = System.currentTimeMillis();

		System.out.println(end - start);
	}
}

public class MyCopy {

	public static void main(String[] args) throws Exception {
		if (args.length != 2) {
			System.out.println("格式错误,请使用如下格式:java copy 源文件地址 目的地址");
			System.exit(1);
		}

		if (Util.exists(args[0])) {
			Util.createParentDirectory(args[0]);
		}

		Util.copyFile(args[0], args[1]);
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值