我想使用 Swift 将一个文件重命名为相同的文件名,只是大小写不同(您可以在 ios playground 中尝试):
filename = "NameWithCase"
newFilename = "Namewithcase"
var url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(filename)
let myText = "Some text to write to file"
try myText.write(to: url, atomically: true, encoding: .utf8)
url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(newFilename)
try myText.write(to: url, atomically: true, encoding: .utf8)
上面的代码给出了一个异常,我真的不知道如何避免:
Error Domain=NSCocoaErrorDomain Code=4 "The file “Namewithcase” doesn’t exist." UserInfo={NSFilePath=..abreviated../tmp/Namewithcase, NSUnderlyingError=0x60000047f8d0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
如果我将新文件的文件名完全更改为例如 Namewithcase2
,一切都会按预期进行。
我在这里想念什么?
最佳答案
这是 MacOS(即 HFS+ 文件系统)的固有问题,因为文件系统不区分大写字母和非大写字母。文件名不区分大小写,只保留大小写(意味着文件名以正确的大小写存储)。 所以唯一的解决办法是在另一个同名但大小写不同的保存操作之前删除文件:
try FileManager.default.removeItem(at: url)
关于ios - 仅通过更改大小写在 Swift 中重命名文件会产生错误 : No such file or directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56270039/