如何使用NSFileManager替换文件或文件夹?

时间:2012-10-03 21:50:24

标签: objective-c

对于使用NSFileManager的“copyItemAtPath”方法,如果存在相同的文件或文件夹,则会发生错误。

NSFileManager中是否有替换功能?

(如果存在相同的文件,则删除并复制如果不存在,只需复制。)

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self generateTableContents];

}


- (void)generateTableContents {

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *appsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [appsDirectory objectAtIndex:0];

    [fileManager changeCurrentDirectoryPath:documentPath];
    [fileManager createDirectoryAtPath:@"user_List1" withIntermediateDirectories:YES attributes:nil error:nil];

    NSString *bundlePath = [[NSBundle mainBundle] resourcePath];

    NSError *error; // to hold the error details if things go wrong
    NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"IMG_0523" ofType:@"JPG"];

    if ([fileManager copyItemAtPath:sourcePath toPath: @"./user_List1/newIMG_0523.JPG" error:&error]) {
        NSLog(@"Copy complete!");
    } else {
        NSLog(@"Copy Failed : %@", error);
    }


    if ([fileManager copyItemAtPath:@"./user_List1" toPath: @"./user_List2" error:&error]) {
        NSLog(@"Copy complete!");
    } else {
        NSLog(@"Copy Failed : %@", error);
    }



}

已完成的结果已经完成。

enter image description here

/Users/nice7285/Library/Caches/appCode10/DerivedData/tempPrg-dd15264d/Build/Products/Debug-iphonesimulator/tempPrg.app/tempPrg
Simulator session started with process 1184
2012-10-04 06:28:32.653 tempPrg[1184:11303] Copy complete!
2012-10-04 06:28:32.672 tempPrg[1184:11303] Copy complete!

Process finished with exit code 143

但已存在的文件夹。

enter image description here

结果失败。

2012-10-04 06:48:31.488 tempPrg[1243:11303] Copy Failed
2012-10-04 06:48:31.497 tempPrg[1243:11303] Copy Failed

2 个答案:

答案 0 :(得分:6)

您需要进行原子保存,例如:

NSData *myData = ...; //fetched from somewhere
[myData writeToFile:targetPath atomically:YES];

但是因为你正在使用copyItemAtPath,所以我不知道是否原子地使用它,所以我只是去寻找快速的黑客攻击:

if ([fileManager fileExistsAtPath:txtPath] == YES) {
    [fileManager removeItemAtPath:txtPath error:&error]
}

NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"txtFile" ofType:@"txt"];
[fileManager copyItemAtPath:resourcePath toPath:txtPath error:&error];

资料来源:IOS: copy a file in documents folder

答案 1 :(得分:0)

从iOS 4(和macOS 10.7)开始,有一种明确的方法可以将一项替换为另一项。它甚至保留原始文件的属性(可选)

- (BOOL)replaceItemAtURL:(NSURL *)originalItemURL withItemAtURL:(NSURL *)newItemURL backupItemName:(NSString *)backupItemName options:(NSFileManagerItemReplacementOptions)options resultingItemURL:(NSURL * _Nullable *)resultingURL error:(NSError * _Nullable *)error;
  

以某种方式替换指定URL上项目的内容   确保没有数据丢失。

replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: