使用IO复制一个文件夹

package com.iotek.inputoutputstream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyDirDemo {

	public static void main(String[] args) {
		try {
			CopyDirUtil.copydir(new File("E:/Word、Excel、PPT、WPS/word文档/向学姐汇报学习情况"),new File("E:/Word、Excel、PPT、WPS/word文档/被复制的文件夹"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
class CopyDirUtil{
	public static void copydir(File srcfile,File desfile) throws IOException{
		desfile.mkdirs();
		if(srcfile!=null){
			File[] files=srcfile.listFiles();//遍历原文件夹中的所有文件和目录
			if(files!=null){
				for(File f:files){
					if(f.isFile()){
						//复制文件
						FileInputStream fis=new FileInputStream(f);
						FileOutputStream fos=new FileOutputStream(
								desfile.getAbsolutePath()+"/"+f.getName());
						byte[] bytes=new byte[1024*10];
						int len=-1;
						while((len=fis.read(bytes))!=-1){
							fos.write(bytes, 0, len);
						}
						fis.close();
						fos.close();
					}else{
						//如果是一个文件夹的话
						copydir(f,new File(desfile.getAbsolutePath()+"/"+
						f.getName()));
					}
				}
			}
		}
	}
}

在 C# 中复制并备份文件夹是一项常见任务,尤其在开发需要文件管理功能的应用程序时。可以通过递归方式遍历源文件夹中的所有文件和子文件夹,并将它们复制到目标路径中。以下是一个完整的实现方案,结合了递归复制、异常处理和性能优化的思路。 ### 递归复制文件夹 使用 `System.IO` 命名空间中的 `Directory` 和 `File` 类,可以实现对文件夹及其子结构的复制。以下代码展示了如何递归复制整个文件夹及其内容: ```csharp using System; using System.IO; class FolderCopier { public static void CopyFolder(string sourcePath, string destinationPath) { if (!Directory.Exists(destinationPath)) Directory.CreateDirectory(destinationPath); foreach (string file in Directory.GetFiles(sourcePath)) { string destFile = Path.Combine(destinationPath, Path.GetFileName(file)); File.Copy(file, destFile, true); } foreach (string dir in Directory.GetDirectories(sourcePath)) { string destDir = Path.Combine(destinationPath, Path.GetFileName(dir)); CopyFolder(dir, destDir); } } } ``` 此方法会创建目标路径下的所有子目录,并复制所有文件,适用于大多数基本的文件夹备份需求[^1]。 ### 异常处理与权限问题 在复制过程中,可能会遇到权限不足或文件被锁定的情况,导致复制中断。为了增强程序的健壮性,应在复制操作中加入异常处理机制: ```csharp public static void SafeCopyFolder(string sourcePath, string destinationPath) { try { if (!Directory.Exists(destinationPath)) Directory.CreateDirectory(destinationPath); foreach (string file in Directory.GetFiles(sourcePath)) { string destFile = Path.Combine(destinationPath, Path.GetFileName(file)); try { File.Copy(file, destFile, true); } catch (Exception ex) { Console.WriteLine($"复制文件 {file} 时出错: {ex.Message}"); } } foreach (string dir in Directory.GetDirectories(sourcePath)) { string destDir = Path.Combine(destinationPath, Path.GetFileName(dir)); SafeCopyFolder(dir, destDir); } } catch (Exception ex) { Console.WriteLine($"复制文件夹 {sourcePath} 时出错: {ex.Message}"); } } ``` 上述代码在复制文件和目录时都加入了 `try-catch` 块,确保即使某个文件复制失败,整个任务也不会中断,同时输出错误信息以便排查问题。 ### 多线程与进度条实现 如果复制文件夹较大,可能会导致界面卡顿。为了避免这种情况,可以将复制操作放在后台线程中执行,并通过事件或委托机制更新进度条。以下是一个使用 `BackgroundWorker` 的简要示例: ```csharp private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { string[] args = (string[])e.Argument; string source = args[0]; string destination = args[1]; SafeCopyFolder(source, destination); } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { progressBar.Value = e.ProgressPercentage; } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { MessageBox.Show("复制完成!"); } ``` 在窗体应用中,可以将 `SafeCopyFolder` 方法与 `BackgroundWorker` 结合,实现非阻塞的复制操作,并通过 `ReportProgress` 方法更新进度条。 ### 性能优化与测试 对于大规模文件夹(如包含数万个文件的目录),建议选择适当的测试用例进行验证。例如,`C:\Windows\SysWOW64\` 是一个大小约为 1GB、包含 1.4 万个文件和 380 个子文件夹的典型测试目录。但由于系统目录受保护,直接复制可能会失败,因此可以先将文件复制到内存盘(如 Ramdisk)进行测试。 ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值