如何在Swift中更改文档文件夹中的文件名

4

我有一些文件位于我的文档文件夹中。我将这些文件命名为 "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)
}

请帮我解决这个问题。


解决这个问题。问题是什么?未经用户同意,您无权访问那里的文件。您是如何访问它们的? - El Tomato
NSDocument 标签是用来做什么的? - El Tomato
1个回答

3

您只需要获取目录的内容,过滤掉名称以"data_"开头的URL,遍历这些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循环。 - Tapan Raut
Pdf 是文件路径的扩展名。 - Leo Dabus
你是在使用macOS还是iOS?如果你正在使用macOS,你需要禁用沙盒功能。 - Leo Dabus
1
非常感谢 @Leo Dabus。我的代码现在可以工作了。 - Tapan Raut

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