gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 03:28:49 24 4
gpt4 key购买 nike

基本上我正在寻找一种方法将文件系统中的两个文件夹与 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;
}
}
}
}

关于ios - 使用 NSFileManager 合并文件夹,仅覆盖现有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19054953/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com