在 Swift 中覆盖文件中的前 N 个字节
Overwriting the first N bytes in a file in Swift
我正在尝试用我自己的数据替换 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()
我把它留给 reader 来处理处理可选值和需要捕获错误。
我正在尝试用我自己的数据替换 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()
我把它留给 reader 来处理处理可选值和需要捕获错误。