我已经读了
Read and write data from text file
我需要将数据(一个字符串)附加到我的文本文件的末尾.
一个明显的方法是从磁盘读取文件,并将字符串附加到其末尾并将其写回来,但是效率不高,尤其是在处理大文件并经常执行时.
所以问题是“如何将字符串附加到文本文件的末尾,而不读取文件并写回整个事物”?
到目前为止我有:
let dir:NSURL = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.CachesDirectory,inDomains: NSSearchPathDomainMask.UserDomainMask).last as NSURL let fileurl = dir.URLByAppendingPathComponent("log.txt") var err:NSError? // until we find a way to append stuff to files if let current_content_of_file = NSString(contentsOfURL: fileurl,encoding: NSUTF8StringEncoding,error: &err) { "\(current_content_of_file)\n\(NSDate()) -> \(object)".writeToURL(fileurl,atomically: true,error: &err) }else { "\(NSDate()) -> \(object)".writeToURL(fileurl,error: &err) } if err != nil{ println("CANNOT LOG: \(err)") }
你应该使用NSFileHandle,它可以是
seek to the end of the file
原文链接:https://www.f2er.com/swift/319791.htmllet dir:NSURL = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.CachesDirectory,inDomains: NSSearchPathDomainMask.UserDomainMask).last as NSURL let fileurl = dir.URLByAppendingPathComponent("log.txt") let string = "\(NSDate())\n" let data = string.dataUsingEncoding(NSUTF8StringEncoding,allowLossyConversion: false)! if NSFileManager.defaultManager().fileExistsAtPath(fileurl.path!) { var err:NSError? if let fileHandle = NSFileHandle(forWritingToURL: fileurl,error: &err) { fileHandle.seekToEndOfFile() fileHandle.writeData(data) fileHandle.closeFile() } else { println("Can't open fileHandle \(err)") } } else { var err:NSError? if !data.writeToURL(fileurl,options: .DataWritingAtomic,error: &err) { println("Can't write \(err)") } }