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

S.J*_*Lim 2 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);
    }



}
Run Code Online (Sandbox Code Playgroud)

已完成的结果已经完成.

在此输入图像描述

/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
Run Code Online (Sandbox Code Playgroud)

但是当已经存在的文件夹.

在此输入图像描述

结果失败.

2012-10-04 06:48:31.488 tempPrg[1243:11303] Copy Failed
2012-10-04 06:48:31.497 tempPrg[1243:11303] Copy Failed
Run Code Online (Sandbox Code Playgroud)

Luk*_*uke 6

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

NSData *myData = ...; //fetched from somewhere
[myData writeToFile:targetPath atomically:YES];
Run Code Online (Sandbox Code Playgroud)

但是因为你正在使用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];
Run Code Online (Sandbox Code Playgroud)

来源:IOS:复制文件夹中的文件