1、拷貝到目標目錄的時候,如果文件已經存在則會直接失敗
2、目標目錄必須是文件
貼一段別人寫 文章
今天我用NSFileManager 文件拷貝函數copyItemAtPath:toPath:error:拷貝文件的時候,一直出現一下錯誤:
Error Domain=NSPOSIXErrorDomain Code=17 “The operation couldn’t be completed. File exists” UserInfo=0x9d37050 {NSUserStringVariant=Copy, NSFilePath=/Users/kimziv/Library/Application Support/iPhone Simulator/4.2/Applications/0110275A-4939-452E-BA34-CADBB63F2042/Documents/resources/ppt/media/image1.jpeg, NSDestinationFilePath=/Users/kimziv/Library/Application Support/iPhone Simulator/4.2/Applications/0110275A-4939-452E-BA34-CADBB63F2042/Documents}
后來仔細看官方文檔發現,我是該函數的第二個參數dstPath我用錯了,要以文件名結尾。
Discussion
If srcPath is a file, the method creates a file at dstPath that holds the exact contents of the original file (this includes BSD special files). If srcPath is a directory, the method creates a new directory at dstPath and recursively populates it with duplicates of the files and directories contained in srcPath, preserving all links. The file specified in srcPath must exist, while dstPath must not exist prior to the operation. When a file is being copied, the destination path must end in a filename—there is no implicit adoption of the source filename. Symbolic links are not traversed but are themselves copied. File or directory attributes—that is, metadata such as owner and group numbers, file permissions, and modification date—are also copied.
NSString* fileName=@"test.jpg";
NSString* resourceDirectory = [[NSBundle mainBundle] resourcePath];
NSString* srcPath = [path stringByAppendingPathComponent:fileName];
NSArray* paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory= [paths objectAtIndex:0];
NSString* dstPath=[documentsDirectory stringByAppendingPathComponent:fileName];//這里要特別主意,目標文件路徑一定要以文件名結尾,而不要以文件夾結尾
NSError* error=nil;
[[NSFileManager defaultManager]copyItemAtPath:srcPath toPath:dstPath error:&error ];
if (error!=nil) {
NSLog(@"%@", error);
NSLog(@"%@", [error userInfo]);
}