ios – 使用NSFileManager合并文件夹,仅覆盖现有文件

基本上我正在寻找一种方法来将文件系统中的两个文件夹与 cocoa API合并:

我有一个包含文件和子文件夹的文件夹,我想将其复制到文件系统中的其他位置.
在我的目标路径中,已存在同名文件夹,该文件夹也可能包含文件文件夹.

现在我想用我的源文件夹的新内容覆盖我的目标文件夹(或其子文件夹)中的现有文件,如果它们具有相同的名称.
我想要保留的所有其余文件都不会受到影响.

sourcefolder
   |
   - file1
   - subfolder
       - file2


destinationfolder
   |
   - file3
   - subfolder
       - file2
       - file4


resultingfolder
   |
   - file1
   - file3
   - subfolder
       - file2      <-- version from source folder
       - file4

我怎样才能做到这一点?
非常感谢你的帮助!

解决方法

我到处搜索但一无所获.所以我想出了自己的解决方案,利用NSDirectoryEnumerator.这应该适用于图表(覆盖旧文件).希望能帮助到你.
- (void)mergeContentsOfPath:(Nsstring *)srcDir intoPath:(Nsstring *)dstDir error:(NSError**)err {

    NSLog(@"- mergeContentsOfPath: %@\n intoPath: %@",srcDir,dstDir);

    NSFileManager *fm = [NSFileManager defaultManager];
    NSDirectoryEnumerator *srcDirEnum = [fm enumeratorAtPath:srcDir];
    Nsstring *subPath;
    while ((subPath = [srcDirEnum nextObject])) {

        NSLog(@" subPath: %@",subPath);
        Nsstring *srcFullPath =  [srcDir stringByAppendingPathComponent:subPath];
        Nsstring *potentialDstPath = [dstDir stringByAppendingPathComponent:subPath];

        // Need to also check if file exists because if it doesn't,value of `isDirectory` is undefined.
        BOOL isDirectory = ([[NSFileManager defaultManager] fileExistsAtPath:srcFullPath isDirectory:&isDirectory] && isDirectory);

        // Create directory,or delete existing file and move file to destination
        if (isDirectory) {
            NSLog(@"   create directory");
            [fm createDirectoryAtPath:potentialDstPath withIntermediateDirectories:YES attributes:nil error:err];
            if (err && *err) {
                NSLog(@"ERROR: %@",*err);
                return;
            }
        }
        else {
            if ([fm fileExistsAtPath:potentialDstPath]) {
                NSLog(@"   removeItemAtPath");
                [fm removeItemAtPath:potentialDstPath error:err];
                if (err && *err) {
                    NSLog(@"ERROR: %@",*err);
                    return;
                }
            }

            NSLog(@"   moveItemAtPath");
            [fm moveItemAtPath:srcFullPath toPath:potentialDstPath error:err];
            if (err && *err) {
                NSLog(@"ERROR: %@",*err);
                return;
            }
        }
    }
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...