我试图用我自己的数据替换 Swift 文件中的前 N 个字节,保持文件的其余部分不变,例如我有字符串 "OOPS"
,文件(任意长度)当前包含 Look, a daisy
,我希望它包含 OOPS, a daisy
。我发现内置函数不能满足我的要求:
try "OOPS".write(to: path, atomically: false, encoding: String.Encoding.utf8)
替换整个文件,
let outputStream = OutputStream(url: outputURL, append: false)
outputStream.write("OOPS", maxLength: 4)
的行为方式相同,并且将 append
设置为 true
显然会将我的文本附加到文件末尾。有没有一种简单的方法来获得我想要的行为?
最佳答案
使用FileHandle
。
let handle = FileHandle(forWritingTo: outputURL)
handle.seek(toFileOffset: 0)
handle.write("OOPS".data(using: .utf8))
handle.closeFile()
我将其留给读者来处理处理选项和需要捕获错误。
关于swift - 在 Swift 中覆盖文件中的前 N 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43241476/