How to rename a file using NSFileManager

后端 未结 4 1662
[愿得一人]
[愿得一人] 2020-12-24 05:51

I have a single file named a.caf in the documents directory. I would like to rename it when user types into a UITextField and presses change (t

相关标签:
4条回答
  • 2020-12-24 06:01

    You can use moveItemAtPath.

    NSError * err = NULL;
    NSFileManager * fm = [[NSFileManager alloc] init];
    BOOL result = [fm moveItemAtPath:@"/tmp/test.tt" toPath:@"/tmp/dstpath.tt" error:&err];
    if(!result)
        NSLog(@"Error: %@", err);
    [fm release];
    
    0 讨论(0)
  • 2020-12-24 06:10

    This is the function by daehan park to converted to Swift 3:

    func moveFile(pre: String, move: String) -> Bool {
        do {
            try FileManager.default.moveItem(atPath: pre, toPath: move)
            return true
        } catch {
            return false
        }
    }
    
    0 讨论(0)
  • 2020-12-24 06:17

    To keep this question up-to-date, I'm adding the Swift version as well:

    let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
    let originPath = documentDirectory.stringByAppendingPathComponent("/tmp/a.caf")
    let destinationPath = documentDirectory.stringByAppendingPathComponent("/tmp/xyz.caf")
    
    var moveError: NSError?
    if !manager.moveItemAtPath(originPath, toPath: destinationPath, error: &moveError) {
        println(moveError!.localizedDescription)
    }
    
    0 讨论(0)
  • 2020-12-24 06:22

    Worked on Swift 2.2

    func moveFile(pre: String, move: String) -> Bool {
        do {
            try NSFileManager.defaultManager().moveItemAtPath(pre, toPath: move)
            return true
        } catch {
            return false
        }
    }
    
    0 讨论(0)
提交回复
热议问题