How to rename a file using NSFileManager

2020-02-17 06:52发布

问题:

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 (the text entered in the UITextField should be the new filename).

How can I do this?

回答1:

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];


回答2:

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)
}


回答3:

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
    }
}


回答4:

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
    }
}