递归实现文件夹copy

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * 递归实现文件夹copy
 */
public class Test3 {
	public static void main(String[] args){
		File file = new File("F:\\1");
		File file2 = new File("F:\\2");
		if (file.getAbsolutePath().equals(file2.getAbsolutePath())) {
			System.out.println("不可copy(原因:可能是同一个文件或文件夹)");
			return;
		}
		// 源目录不存在
		if (!file.exists()) {
			System.out.println("源目录或源文件不存在");
			return;
		}
		// file是文件,直接copy
		if (file.isFile()) {
			// file为文件则直接copy文件,copy完成后终止程序
			System.out.println("正在copy文件,请稍后");
			copyFile(file, file2);
			System.out.println("文件copy完成");
			return;
		}
		// file是文件夹
		if (file.isDirectory()) {
			System.out.println("正在copy文件夹,请稍后");
			copyAllFiles(file,file2);
			System.out.println("文件夹copy完成");
		}else {
			System.out.println("抱歉,文件夹copy失败");
		}
	}
	public static void copyAllFiles(File file,File file2) {
		File[] listFiles = file.listFiles();
		if (listFiles!=null) {
			for (File f : listFiles) {
				File temp = new File(file2.getAbsoluteFile(),f.getName());
				if (f.isDirectory()) {
					temp.mkdirs();
					copyAllFiles(f,temp);
				}else {
					copyFile(f, temp);
				}
			}
		}
	}
	public static void copyFile(File f1,File f2){
		FileInputStream fileInputStream = null;
		FileOutputStream fileOutputStream = null;
		try {
			fileInputStream = new FileInputStream(f1);
			fileOutputStream = new FileOutputStream(f2);
			int length = 0;
			byte[] bytes = new byte[1024];
			while ((length=fileInputStream.read(bytes))!=-1) {
				fileOutputStream.write(bytes,0,length);
				//System.out.println("写入完毕");
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if (fileInputStream!=null) {
					fileInputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (fileOutputStream!=null) {
					fileOutputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值