【问题标题】:How to change file name in document folder in swift如何在swift中更改文件夹中的文件名
【发布时间】:2021-04-02 14:23:42
【问题描述】:

我的文件夹中有一些文件。我正在保存“data_20201223163209.pdf”、“data_20201223171831.pdf”、“data_20201222171831.pdf”、“data_20201221171831.pdf”等文件。现在我想用“newdata”等其他字符串替换“data”。所以我的文件应该是“newdata_20201223163209.pdf”、“newdata_20201223171831.pdf”、“newdata_20201222171831.pdf”、“newdata_20201221171831.pdf”

我的代码:

do {
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let documentDirectory = URL(fileURLWithPath: path)
    let originPath = documentDirectory.appendingPathComponent("data")
    let destinationPath = documentDirectory.appendingPathComponent("newdata")
    try FileManager.default.moveItem(at: originPath, to: destinationPath)
} catch {
    print(error)
}

请帮我解决这个问题

【问题讨论】:

  • “解决这个问题” 问题是什么?未经用户同意,您不得访问那里的文件。您如何访问它们?
  • NSDocument 标签是干什么用的?

标签: swift nsfilemanager


【解决方案1】:

您只需要获取目录的内容,过滤名称以“data_”开头的 url,迭代这些 url 并重命名每个将其移动到具有新名称的相同目录。请注意,这假定目标位置没有具有新名称的文件。

// Get the documents url
let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
    // Get its contents
    let contents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
    print(contents)
    // filter the contents that starts with "data_"
    let dataFiles = contents.filter { $0.lastPathComponent.hasPrefix("data_") }
    // iterate the source files
    for srcURL in dataFiles {
        // create the destinations appending "newdata_" + the source lastPathComponent dropping its "data_" prefix
        let dstURL = documentsUrl.appendingPathComponent("newdata_" + srcURL.lastPathComponent.dropFirst(5))
        // move/rename your files
        try FileManager.default.moveItem(at: srcURL, to: dstURL)
    }
} catch {
    print(error)
}

【讨论】:

  • 嗨@Leo 感谢您的回答。当我们检查 lastPathComponent 时,“pdf”是这里的最后一个路径。所以它的前缀如下:-“data_20201223163209。”,“data_20201223171831。”,“data_20201222171831”。等等,所以它没有进入 for 循环。
  • pdf是路径扩展
  • 您使用的是 macOS 还是 iOS?如果您使用的是 macOS,则需要禁用沙盒功能
  • 非常感谢@Leo Dabus。我的代码现在可以工作了
猜你喜欢
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 2012-02-02
  • 2019-04-27
  • 2023-03-18
  • 2018-07-28
  • 2013-05-20
  • 2018-03-31
相关资源
最近更新 更多