(java基础)将指定目录(包含内容)复制到另一个目录中

本文介绍了一个Java程序案例,该程序能够将一个指定目录及其所有内容复制到另一个目录中。通过对源目录进行遍历,复制文件及子目录,并在目标位置重建相同的目录结构。文章通过具体代码展示了如何使用FileInputStream和FileOutputStream来逐个复制文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
 * 将指定目录(包含内容)复制到另一个目录中(案例分析与实现)
 */
public class CopyFileTest {
	public static void main(String[] args) throws IOException {
		// 源目录
		File src = new File("H:\\Test");
		// 目的地
		File dest = new File("c:\\");
		copyFile(src, dest);
	}
	
	public static void copyFile(File src,File dest) throws IOException{
		// 在目的地创建文件夹  c:\\Test\\day09\\avi
		File newFile = new File(dest,src.getName());
		// 判断拼接成的路径是否存在
		if(!newFile.exists()){
			newFile.mkdirs();
		}
		// 获取源目录中的所有的文件和文件夹
		File[] files = src.listFiles();
		for (File file : files) {
			if(file.isFile()){
				// 开始复制文件
				FileInputStream fis = new FileInputStream(file);
				// c:\\Test\\day09\\ppt
				FileOutputStream fos = new FileOutputStream(new File(newFile,file.getName()));
				byte[] b = new byte[1024];
				int len;
				while((len  = fis.read(b)) !=-1){
					fos.write(b, 0, len);
				}
				
				fos.close();
				fis.close();
				
			}else if(file.isDirectory()){
				copyFile(file, newFile);
			}
		}
	}
}

		

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值