使用 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);
}
}
执行结果完成。
/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
但是当已经存在文件夹时。
结果是失败。
2012-10-04 06:48:31.488 tempPrg[1243:11303] Copy Failed
2012-10-04 06:48:31.497 tempPrg[1243:11303] Copy Failed