文件夹的拷贝

package com.io.test;

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;

/**
 * 
 * @author 丢了风筝的线
 * @see 文件夹的拷贝
 */
public class Directory {
	public static void main(String[] args) {

		// 要拷贝的文件夹路径
		String originalPath = "D:/新建文件夹/20191014优就业/Java/JavaSECode/day24";

		// 目标路径
		String targetPath = "C:/Users/Administrator/Desktop";
		traversalFile(originalPath, targetPath);

	}

	public static void traversalFile(String originalPath, String targetPath) {

		// 创建原文件操作对象
		File originalFile = new File(originalPath);

		// 拷贝到那里
		targetPath += "/" + originalFile.getName();
		System.out.println(targetPath);

		// 判断传入的文件路径是文件夹还是文件
		if (!originalFile.isDirectory()) {

			// 复制文件
			Copyfile(originalPath, targetPath);
		} else {

			// 创建拷贝目录
			File targetFile = new File(targetPath);
			targetFile.mkdirs();

			// 循环遍历原文件中的每个文件夹和文件
			File[] files = originalFile.listFiles();
			for (File file : files) {

				traversalFile(file.getAbsolutePath(), targetPath);

			}
		}

	}

	public static void Copyfile(String originalPath, String targetPath) {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {

			// 输入流对象
			inputStream = new FileInputStream(originalPath);

			// 输出流对象
			outputStream = new FileOutputStream(targetPath);

			// 读取文件内容
			byte[] flush = new byte[1024];
			int len;
			while ((len = inputStream.read(flush)) != -1) {

				// 写入到目标文件
				outputStream.write(flush, 0, len);

				// 刷新
				outputStream.flush();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		} finally {

			// 关闭流
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {

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

					e.printStackTrace();
				}
			}
		}
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值