复制多级文件,将一个文件夹中的所有内容复制到另一个文件夹中

复制多级文件,将一个文件夹中的所有内容复制到另一个文件夹中。

设计递归方法,通过传入源文件和目的文件,将源文件中内容完全复制到目的文件中:
代码如下:

private static void copyFolder(File srcFile, File destFile) throws IOException {  //srcFile为源文件,destFile为目的文件
		if (srcFile.isDirectory()) {
			File newFolder = new File(destFile, srcFile.getName());
			newFolder.mkdir();
			File[] fileArray = srcFile.listFiles();
			for (File file : fileArray) {
				copyFolder(file, newFolder);
			}
		} else {
			File newFile = new File(destFile, srcFile.getName());
			copyFile(srcFile, newFile);
		}
	}

定义复制文件的方法:(运用字节缓冲流)

private static void copyFile(File srcFile, File newFile) throws IOException {
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
		byte[] bys = new byte[1024];
		int len = 0;
		while ((len = bis.read(bys)) != -1) {
			bos.write(bys, 0, len);
		}
		bos.close();
		bis.close();
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值