微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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;
            }
        }
    }
}

原文地址:https://www.jb51.cc/iOS/328582.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐