案例——复制文件夹

复制文件夹 

/**
 * 复制文件夹操作
 * @param sourceDir 源文件夹
 * @param destDir 目标文件夹
 * @throws FileNotFoundException 
 */
public static void copyDir(File sourceFile, File destFile) throws FileNotFoundException {
	// 1.判断源文件是否存在
	if(!sourceFile.exists()) {
		throw new FileNotFoundException("源文件夹不存在!");
	}
	// 2.如果目标文件不存在,则新建目标文件夹
	if(!destFile.exists()) {
		destFile.mkdirs(); 
	}
	// 3.获取源文件夹中所有的子文件(包含文件和文件夹)
	File[] files = sourceFile.listFiles();
	for(File file : files) {
		// 3.1如果是文件,则直接复制文件即可
		if(file.isFile()) {
			// 执行拷贝文件操作
			copyFile(file, new File(destFile, file.getName()));
		}
		// 3.2如果是文件夹,则递归调用
		else {
			copyDir(file, new File(destFile, file.getName()));
		}
	}
}

复制文件 

/**
 * 文件拷贝
 * @param sourceFile 需要拷贝的文件
 * @param destFile 把文件拷贝到哪里去
 */
public static void copyFile(File sourceFile, File destFile) {
	BufferedInputStream bis = null;
	BufferedOutputStream bos = null;
	try {
		// 1.文件输入流
		FileInputStream fis = new FileInputStream(sourceFile);
		bis = new BufferedInputStream(fis);
		// 2.文件输出流
		FileOutputStream fos = new FileOutputStream(destFile);
		bos = new BufferedOutputStream(fos);
		// 3.读取数据
		byte[] by = new byte[1024];
		int len = 0;
		while((len = bis.read(by)) != -1) {
			// 4.写入数据
			bos.write(by, 0, len);
		}
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if(bos != null) {
			try {
				bos.close(); // 关闭输出流
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(bis != null) {
			try {
				bis.close(); // 关闭输入流
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

main方法中调用拷贝文件夹的方法

public static void main(String[] args) {
	// 要复制的文件对象
	File sourceDirFile = new File("E:\\WH_180920_JAVA");
	//复制的位置
	File destDirFile = new File("E:\\BJ_JAVA");
	try {
		copyDir(sourceDirFile, destDirFile);
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	}
}

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

深山老林.

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

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

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

打赏作者

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

抵扣说明:

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

余额充值