Java复制文件夹

以下是复制文件夹的代码

package com.carlinfo.filetree;

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

public class CopyFolder2 {

public static void main(String[] args) {
	/* 准备源路径 */
	String path = "H:\\test2";
	File sourceFile = new File(path);
	/* 目标路径 */
	String path2 = "h:\\test\\c";
	File TargetFile = new File(path2);
	copy(sourceFile, TargetFile);
            System.out.println("复制成功!");
}

public static void copy(File sourceFile, File TarFile) {
	String str = "";
	/* 判断该文件是不是文件夹,是文件,直接复制文件 */
	if (!sourceFile.isDirectory()) {
		cy(sourceFile, TarFile);
	} else {
		str = TarFile.getPath() + "\\" + sourceFile.getName();
		System.out.println("--创建文件夹-->" + str);
		File fs = new File(str);
		fs.mkdir();
		/* 将该文件夹中的文件取出来 */
		File[] listFiles = sourceFile.listFiles();
		for (int i = 0; i < listFiles.length; i++) {
			/* 对文件夹遍历,判断是文件还是文件夹 */
			if (!listFiles[i].isDirectory()) {
				cy(listFiles[i], fs);
			} else {
				/* 如果是文件夹,继续调自己,递归 */
				copy(listFiles[i], fs);
			}

		}
	}
}

/**
 * 复制文件
 * 用到io字节流
 * 
 * @param sourceFile
 * @param TarFile
 */
public static void cy(File sourceFile, File TarFile) {
	/* 用于拼装路径,因为目标文件不存在 */
	String str = "";
	/* 准备管子 */
	FileInputStream fis = null;
	FileOutputStream fos = null;
	BufferedInputStream bis = null;
	BufferedOutputStream bos = null;
	/* 准备容器 */
	byte[] b = new byte[1024];
	/* 拼装路径 */
	str = TarFile.getPath() + "\\" + sourceFile.getName();
	System.out.println("--创建文件--" + str);
	File file = new File(str);
	try {
		file.createNewFile();

		fis = new FileInputStream(sourceFile);
		bis = new BufferedInputStream(fis);

		fos = new FileOutputStream(file);
		bos = new BufferedOutputStream(fos);

		int len = 0;
		while ((len = bis.read(b)) != -1) {
			/* 写数据 */
			bos.write(b, 0, len);
		}
		bos.flush();
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		try {
			if (bis != null) {
				/* 记得关闭管子 */
				bis.close();
				bis = null;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			if (bos != null) {
				/* 关闭管子 */
				bos.close();
				bos = null;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值