How to rename a file using NSFileManager

2020-02-17 06:36发布

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?

4条回答
狗以群分
2楼-- · 2020-02-17 07:02

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
    }
}
查看更多
Summer. ? 凉城
3楼-- · 2020-02-17 07:03

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楼-- · 2020-02-17 07:12

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];
查看更多
Explosion°爆炸
5楼-- · 2020-02-17 07:14

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)
}
查看更多
登录 后发表回答