文档目录中的图像路径替换



要使用NSFileManager,如果存在图像路径或文件夹,如何替换文档目录中的新图像路径(或)文件夹。

NSFileManager中有替换功能吗?(如何在文档目录中用新的图像路径替换图像路径位置)

你想写一个图像,只需把它写到文件。如果同一路径中存在同名图像,则它将被覆盖

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
UIImage * imageToSave = [UIImage imageNamed:@"Icon.png"];
NSData * binaryImageData = UIImagePNGRepresentation(imageToSave);
[binaryImageData writeToFile:[basePath  stringByAppendingPathComponent:@"myfile.png"] atomically:YES];

不能使用 NSFileManager 替换路径,因为您已经保存了 ImagePath。现在您可以检查该路径是否存在,然后您可以使用以下命令删除该 filePath:

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

现在保存您的新路径。

如果要替换内容,则只需先删除,然后使用

writeToFile:filePath
    NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString* foofile = [documentsPath stringByAppendingPathComponent:filename];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
    NSLog(fileExists ? @"Yes" : @"No");
    if (fileExists == YES)
    {
        NSString *filePath = [NSString stringWithFormat:@"%@/%@", aDocumentsDirectory,filename];
        NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
        [data1 writeToFile:filePath atomically:YES];
    }

最新更新