用java复制指定文件夹

通过IO流复制指定文件夹到指定目录(Java)

思路
  • 1、复制子文件夹
    • 1)、创建源
    • 2)、创建下级File对象
    • 3)、判断目标文件夹是否存在
    • 4)、判断是文件夹还是文件(若为文件夹则改变目标源)
    • 5)、若是文件夹则创建该文件夹的对象再进行递归,否则复制文件
  • 2、复制文件
    • 1)、选择流
    • 2)、操作
    • 3)、释放资源

代码

public class Copy_dir {

	public static void main(String[] args) {
		
		String srcPath = "C:/Users/xxx's_computer/eclipse-workspace/IO_study01/src";
		String destPath = "C:/Users/xxx's_computer/eclipse-workspace/IO_study02/dir/test";
		copyDir(srcPath, destPath);
	}
	
	public static void copyDir(String srcPath, String destPath) {
		//创建源
		File src = new File(srcPath);
		File dest = new File(destPath);
		//创建下级File对象
		File [] fileArray = src.listFiles();
		//判读那目标文件夹是否存在
		if (!dest.exists()) {
			dest.mkdirs();
		}
		for (File file : fileArray) {
			//判断是文件夹还是文件
			if (file.isDirectory()) {
				String dirName = file.getName();
				File newDest = new File(dest, dirName);
				//递归,用来复制源文件的所有文件夹(不含文件)
				copyDir(file.getPath(), newDest.getPath());
			} else {
				String fileName = file.getName();
				File destFile = new File(dest, fileName);
				copy(file, destFile);
			}
		}
	}
	
	public static void copy(File file, File destFile) {
		
		//选择流,分别为输入、输出流
		InputStream is = null;
		OutputStream os = null;
		try {
			is = new FileInputStream(file);
			os = new FileOutputStream(destFile);
			byte [] dirsDatas = new byte[1024*100];//缓冲容器
			int len = -1;
			while((len = is.read(dirDatas)) != -1) {
				os.write(dirsDatas, 0, len);
			}
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			//释放资源 原则: 分别关闭,先打开的后关闭
			try {
				if (os != null) {
					os.close();
				} 
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			try {
				if (is != null) {
					is.close();
				} 
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	
	}
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鹏晓星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值