How to overwrite a file with NSFileManager when copying?

后端 未结 9 677
广开言路
广开言路 2020-12-02 14:13

I\'m using this method to copy a file:

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

I want to overwrite a fi

相关标签:
9条回答
  • 2020-12-02 14:39

    I think what you're looking for is the NSFileManagerDelegate protocol method:

    - (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error copyingItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath;
    

    From this method, you can decide what to do with the existing file (rename/delete) and then proceed with the copy.

    0 讨论(0)
  • 2020-12-02 14:43

    Detect file exists error, delete the destination file and copy again.

    Sample code in Swift 2.0:

    class MainWindowController: NSFileManagerDelegate {
    
        let fileManager = NSFileManager()
    
        override func windowDidLoad() {
            super.windowDidLoad()
            fileManager.delegate = self
            do {
                try fileManager.copyItemAtPath(srcPath, toPath: dstPath)
            } catch {
                print("File already exists at \'\(srcPath)\':\n\((error as NSError).description)")
            }
        }
    
        func fileManager(fileManager: NSFileManager, shouldProceedAfterError error: NSError, copyingItemAtPath srcPath: String, toPath dstPath: String) -> Bool {
            if error.code == NSFileWriteFileExistsError {
                do {
                    try fileManager.removeItemAtPath(dstPath)
                    print("Existing file deleted.")
                } catch {
                    print("Failed to delete existing file:\n\((error as NSError).description)")
                }
                do {
                    try fileManager.copyItemAtPath(srcPath, toPath: dstPath)
                    print("File saved.")
                } catch {
                    print("File not saved:\n\((error as NSError).description)")
                }
                return true
            } else {
                return false
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-02 14:43

    I think the possibility of the nanosecond you mensioned is feeble. so stick to the first method of removing the existing file and copying the new file.

    0 讨论(0)
  • 2020-12-02 14:45

    This is for improvement of 'Swift 3 and above' of question 'Move file and override [duplicate]' which is marked duplicate of this question.

    To move file from sourcepath(string) to DestinationPath(string). Delete the existing file if same name file already exists at DestinationPath.

    // Set the correct path in string in 'let' variables.
    let destinationStringPath = ""
    let sourceStringPath = ""
    
    let fileManager:FileManager = FileManager.default
    do
    {
        try fileManager.removeItem(atPath: sourceStringPath)
    }
    catch
    {
    }
    
    do
    {
        try fileManager.moveItem(atPath: sourceStringPath, toPath: destinationStringPath)
    }
    catch
    {
    }
    
    0 讨论(0)
  • 2020-12-02 14:49

    For overwriting files, I prefer

    NSData *imgDta = UIImageJPEGRepresentation(tImg, 1.0);
    
    [imgDta writeToFile:targetPath options:NSDataWritingFileProtectionNone error:&err];
    

    Removing & copying files in loop sometimes doesn't work as intended

    0 讨论(0)
  • 2020-12-02 14:50

    Swift4:

    _ = try FileManager.default.replaceItemAt(previousItemUrl, withItemAt: currentItemUrl)
    
    0 讨论(0)
提交回复
热议问题