我有以下代码写入文件末尾。但是,如何修改行为,以使其创建“ output.txt”(如果不存在)?
谢谢!
func writeFile(){
let str = "\n" + nominationKeyForWhenCellSelected! + "," + "1"
let datafromString = str.data(using: String.Encoding.utf8)
let filename = getDocumentsDirectory().appendingPathComponent("output.txt")
do {
let fileHandle = try FileHandle(forWritingTo: filename)
fileHandle.seekToEndOfFile()
fileHandle.write(datafromString!)
} catch {
}
}
答案 0 :(得分:1)
使用FileManager检查文件是否存在。如果没有,只需写数据,否则按您的做法追加。但是不要忘记关闭文件句柄。
do {
if FileManager.default.fileExists(atPath: filename.path) {
let fileHandle = try FileHandle(forWritingTo: filename)
fileHandle.seekToEndOfFile()
fileHandle.write(datafromString!)
fileHandle.closeFile()
} else {
datafromString.write(to: filename)
}
} catch {
print(error)
}