如何使用NSFileManager重命名文件

42
我在文档目录中有一个名为a.caf的单个文件,我想在用户在UITextField中输入并按下更改时将其重命名(UITextField中输入的文本应成为新文件名)。
我该如何做?

1
这个问题将会回答你的疑问:https://dev59.com/inNA5IYBdhLWcg3wrPyq - Alex Zielenski
4个回答

85

你可以使用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];

这是将文件从一个文件夹移动到另一个文件夹,无论如何它都可以工作,但是当文件名中有空格时它不起作用。例如:路径:/tmp/test file.tt toPath:/tmp/dst path.tt 它是一个 URL,空格会自动转换为 %20。是否有其他可能性可以在不使用 URL / 移动的情况下重命名文件夹? - iOSDude

15
为了让这个问题保持最新,我也会添加Swift版本:

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

我没有及时更新它。谢谢提醒,我会更新答案。 - Michal

9
这是由Daehan Park编写的函数,已经转换为Swift 3,并且可以与Swift 4和5一起使用:
func moveFile(pre: String, move: String) -> Bool {
    do {
        try FileManager.default.moveItem(atPath: pre, toPath: move)
        return true
    } catch {
        return false
    }
}

2

参与开发过Swift 2.2相关项目

func moveFile(pre: String, move: String) -> Bool {
    do {
        try NSFileManager.defaultManager().moveItemAtPath(pre, toPath: move)
        return true
    } catch {
        return false
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接