如何在复制时使用[NSfilemanager defaultmanager]覆盖文件夹? [英] How to overwrite a folder using [NSfilemanager defaultmanager] when copying?

查看:417
本文介绍了如何在复制时使用[NSfilemanager defaultmanager]覆盖文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下行,

[fileManager copyItemAtPath:sourcePath toPath:targetPath error:&error];

我们可以复制文件夹,但如果文件夹已经存在,则会抛出异常文件存在。
为了覆盖单个文件,我们可以通过以下几行来实现:

We can copy a folder but if the folder already exists it throws an exception "File Exists". In order to overwrite a single file, we can achieve it through the following lines:

NSData *myData = [NSData dataWithContentsOfURL:FileURL]; /fetch single file
[myData writeToFile:targetPath atomically:YES];

但我想复制一个现有的文件夹,即覆盖

But I want to copy an already existing folder i.e, overwrite.

编辑
简单可能,我可以在复制之前删除这些项目。

Edit : Simple Possibility , I can remove the items before copying them.

请建议更多可能性。

推荐答案

NSFileManager的默认行为方法是抛出异常/错误文件存在。当文件存在时。但是如果你想使用 NSFileManager 进行覆盖,那么它会为下面提到的api提供一个api replaceItemAtURL 以及第一个解决方案: -

The default behavior of NSFileManager method is to throw an exception/error "File Exists." when the file exists. But still if you want to overwrite using NSFileManager then it provides one api for that which is mentioned below replaceItemAtURL as well in first solution:-

此外,有三种解决方案可以实现这一目标

Also there are three solutions to achieve that

第一个解决方案

[filemanger replaceItemAtURL:url1 
               withItemAtURL:url2
              backupItemName:@"/Users/XYZ/Desktop/test.xml"
                     options:NSFileManagerItemReplacementUsingNewMetadataOnly 
            resultingItemURL:nil error:nil];

使用上述API可以覆盖文件内容。但在此之前,您必须在临时目录中备份源路径。

Using the above API you can overwrite the file contents. But before that you have to take the backup of your source path in your temporary directory.

第二个解决方案

您已经在使用<$ c的问题中提到过$ c> NSData writeToUrl 。

第三种解决方案

trojanfoe在他们的回答中提到过。即删除事先被覆盖的项目。

trojanfoe has mentioned in their answer. i.e. remove the item being overwritten beforehand.

这篇关于如何在复制时使用[NSfilemanager defaultmanager]覆盖文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆