4
您好,我对swift编程颇为陌生,所以如果我犯了明显错误,请耐心等待。我正在尝试将用户通过文本字段输入的数据写入文本文件。我可以通过我在下面写的代码成功地做到这一点。但是,当我试图保存更多的数据时,它将用正在保存的新数据替换文本文件中的现有数据。例如,如果我保存字符串'hello world',然后保存另一个字符串说'再见'。我只会在文本文件中看到字符串'bye'。有没有办法可以修改我的代码,这样我就可以在纺织品的一条线上看到'hello world',在另一条线上看到'再见'。在swift中写入文本文件3
@IBAction func btnclicked(_ sender: Any) {
self.savedata(value: answer.text!)
}
func savedata (value: String){
let fileName = "Test"
let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = DocumentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")
print("FilePath: \(fileURL.path)")
let writeString = NSString(string: answer.text!)
do {
// Write to the file
try writeString.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8.rawValue)
} catch let error as NSError {
print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
给予任何帮助是极大的赞赏 三江源
你应该使用NSFileHandle,它可以寻找到文件的结尾 – Sneha