【问题标题】:How to rename a file using NSFileManager如何使用 NSFileManager 重命名文件
【发布时间】:2011-03-30 20:26:40
【问题描述】:

我在文档目录中有一个名为 a.caf 的文件。我想在用户输入UITextField 并按下更改时重命名它(UITextField 中输入的文本应该是新的文件名)。

我该怎么做?

【问题讨论】:

标签: nsfilemanager


【解决方案1】:

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

【讨论】:

  • 这是将文件从一个文件夹移动到另一个文件夹,无论如何它可以工作,但是当文件名中有空格时它就不能工作。例如:Path:: /tmp/test file.tt toPath: /tmp/dst path.tt 这是一个 url 空间自动转换为 %20。是否有任何其他没有 URL/移动的可能重命名文件夹。??
【解决方案2】:

为了保持这个问题最新,我也添加了 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)
}

【讨论】:

  • 我没有更新它。感谢您的提醒,我会更新答案。
【解决方案3】:

这是 daehan park 转换为 Swift 3 的功能:

func moveFile(pre: String, move: String) -> Bool {
    do {
        try FileManager.default.moveItem(atPath: pre, toPath: move)
        return true
    } catch {
        return false
    }
}

【讨论】:

    【解决方案4】:

    使用 Swift 2.2

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

    【讨论】:

      猜你喜欢
      • 2011-04-10
      • 2020-04-03
      • 2011-01-30
      • 2012-06-01
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多