我设法在swift中读取和写入数据到文件中。但是当我再次将数据写入其中时,我想附加文件,并且还要读取文件的最后10行。 我怎么能这样做?
这是我正在使用的代码 - 阅读:
// Create a FileHandle instance
let file: NSFileHandle? = NSFileHandle(forReadingAtPath: "hello.swift")
if file != nil {
// Read all the data
let data = file?.readDataToEndOfFile()
// Close the file
file?.closeFile()
// Convert our data to string
let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(str!)
}
else {
print("Ooops! Something went wrong!")
}
这是我正在使用的代码 - 写作:
// Set the file path
let path = "myfile.txt"
// Set the contents
let contents = "Here are my file's contents"
do {
// Write contents to file
try contents.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}