ios - 仅通过更改大小写在 Swift 中重命名文件会产生错误 : No such file or directory

标签 ios swift

我想使用 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/

相关文章:

ios - 在同一个类中调用枚举函数内部的函数

ios - iOS 后台模式下调试网络通信

ios - 如何检查子节点是否已被触摸 Swift 3

iphone - 如何更改 iPhone 中导航栏的默认高度

ios - 解析+Swift, "-[Swift._NSContiguousString objectId]: unrecognized selector sent to instance"错误

ios - 如何添加图像点击代码以转到新屏幕?

ios - Swift:在动画期间中途更改 UIImageView 图像

ios - 当您将 UIButton 放入 UITableViewCell 中时,TitleLabel 会损坏

ios - React Native navigator.geolocation.getCurrentPosition 如何自定义 Alert Text Message

ios - Swift 核心数据关系和播种数据