Java实现文件夹复制

使用递归复制文件夹和文件 

package constxiong.interview;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


/**
 * 复制文件夹
 * @author ConstXiong
 * @date 2019-11-13 13:38:19
 */
public class TestCopyDir {

	public static void main(String[] args) {
		String srcPath = "E:/a";
		String destPath = "E:/a_";
		copyDir(srcPath, destPath);
	}
	
	/**
	 * 复制文件夹
	 * @param srcFile
	 * @param destFile
	 */
	public static void copyDir(String srcDirPath, String destDirPath) {
		File srcDir = new File(srcDirPath);
		if (!srcDir.exists() || !srcDir.isDirectory()) {
			throw new IllegalArgumentException("参数错误");
		}
		File destDir = new File(destDirPath);
		if (!destDir.exists()) {
			destDir.mkdirs();
		}
		File[] files = srcDir.listFiles();
		for (File f : files) {
			if (f.isFile()) {
				copyFile(f, new File(destDirPath, f.getName()));
			} else if (f.isDirectory()) {
				copyDir(srcDirPath + File.separator + f.getName(),
						destDirPath + File.separator + f.getName());
			}
		}
	}
	
	/**
	 * 复制文件
	 * @param srcFile
	 * @param destFile
	 */
	public static void copyFile(File srcFile, File destFile) {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		byte[] b = new byte[1024];
		
		try {
			bis = new BufferedInputStream(new FileInputStream(srcFile));
			bos = new BufferedOutputStream(new FileOutputStream(destFile));
			int len;
			while ((len = bis.read(b)) > -1) {
				bos.write(b, 0, len);
			}
			bos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}

 

 


【Java面试题与答案】整理推荐

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值