java基于递归思想的文件拷贝

这段代码原本目的是扫描是否插入U盘,插入的话,自动将U盘文件全部备份到目标文件夹中。

文件目录是树状结构,很有层次感,且每层操作大致相同。复制目录中的文件,不是创建文件夹操作,就是复制文件操作,所以递归思想在这里很适用。

代码如下:

/****
 * 
 * @author wjw
 * @since 2018-02-27
 *
 */
public class Copy {

	public static void main(String[] args) throws IOException,
			InterruptedException {
		// 配置文件配置轮询盘符
		int second = 10;// 轮询文件是否存在时间间隔
		String souPath = "H:/"; // 源路径
		String desPath = "E:/U/test"; // 目标路径
		File file = new File(souPath);
		while (!file.exists()) {
			System.out.println(souPath + "目录不存在!");
			Thread.sleep(1000 * second);
		}
		long beginMillis = System.currentTimeMillis();
		copy(souPath, desPath);
		System.out.println("复制文件约耗时: "
				+ (System.currentTimeMillis() - beginMillis) / 1000 + " s.");
	}

	public static void copy(String souPath, String desPath) throws IOException {
		File dir = new File(souPath);

		if (dir.isDirectory()) {
			System.out.println("开始拷贝目录 " + souPath + " 中的文件到目录 " + desPath
					+ " 中...");
			String[] filesStr = dir.list();
			for (int i = 0; i < filesStr.length; i++) {
				String tempSouPath = souPath + File.separator + filesStr[i];
				String tempDesPath = desPath + File.separator + filesStr[i];
				if (new File(tempSouPath).isDirectory()) {
					createDir(tempDesPath);
					copy(tempSouPath, tempDesPath);
				} else {
					copyFile(tempSouPath, tempDesPath);
				}

			}

			System.out.println(souPath + "目录中的文件拷贝完毕!");
		} else if (dir.isFile()) {

			copyFile(souPath, desPath);

		}

	}

	/****
	 * 创建目录
	 * 
	 * @param dirPath
	 */
	public static void createDir(String dirPath) {
		// System.out.println("创建目录:" + dirPath);
		File file = new File(dirPath);
		if (file != null) {
			if (!file.exists()) {
				file.mkdir();
			}

		}

	}

	/*******
	 * 复制文件
	 * 
	 * @throws IOException
	 */
	public static void copyFile(String sourcePath, String desPath)
			throws IOException {
		System.out.println("       开始拷贝文件  " + sourcePath + "...");
		FileInputStream fis = null;
		FileOutputStream fos = null;
		File file = new File(sourcePath);
		if (file != null && file.isFile()) {
			fis = new FileInputStream(file);
			File des = new File(desPath);
			fos = new FileOutputStream(des);
			int bufferSize = 1024;
			byte[] data = new byte[bufferSize];
			int length = 0;
			while ((length = fis.read(data, 0, bufferSize)) != -1) {
				fos.write(data, 0, length);
			}

		}
		fis.close();
		fos.close();
		System.out.println("   " + desPath + "文件拷贝完毕!");
	}

}



如有错误,欢迎指正!

end

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值