在 Swift 中将文本或数据附加到文本文件 [英] Append text or data to text file in Swift

查看:32
本文介绍了在 Swift 中将文本或数据附加到文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了从文本文件读写数据

我需要将数据(字符串)附加到文本文件的末尾.
一种明显的方法是从磁盘读取文件并将字符串附加到它的末尾并写回它,但它效率不高,特别是如果您正在处理大文件并且经常这样做.

I need to append the data (a string) to the end of my text file.
One obvious way to do it is to read the file from disk and append the string to the end of it and write it back, but it is not efficient, especially if you are dealing with large files and doing in often.

所以问题是如何将字符串附加到文本文件的末尾,而不读取文件并将整个内容写回"?

So the question is "How to append string to the end of a text file, without reading the file and writing the whole thing back"?

到目前为止我有:

    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)
(NSDate()) -> (object)".writeToURL(fileurl, atomically: true, encoding: NSUTF8StringEncoding, error: &err)
    }else {
        "(NSDate()) -> (object)".writeToURL(fileurl, atomically: true, encoding: NSUTF8StringEncoding, error: &err)
    }
    if err != nil{
        println("CANNOT LOG: (err)")
    }

推荐答案

这是 PointZeroTwo 在 Swift 3.0 中的答案的更新,有一个简短的说明 - 在操场上使用简单的文件路径进行测试是可行的,但在我的实际应用程序中,我需要使用 .documentDirectory(或您选择用于读取和写入的任何目录 - 确保它在整个应用程序中保持一致)构建 URL:

Here's an update for PointZeroTwo's answer in Swift 3.0, with one quick note - in the playground testing using a simple filepath works, but in my actual app I needed to build the URL using .documentDirectory (or which ever directory you chose to use for reading and writing - make sure it's consistent throughout your app):

extension String {
    func appendLineToURL(fileURL: URL) throws {
         try (self + "
").appendToURL(fileURL: fileURL)
     }

     func appendToURL(fileURL: URL) throws {
         let data = self.data(using: String.Encoding.utf8)!
         try data.append(fileURL: fileURL)
     }
 }

 extension Data {
     func append(fileURL: URL) throws {
         if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
             defer {
                 fileHandle.closeFile()
             }
             fileHandle.seekToEndOfFile()
             fileHandle.write(self)
         }
         else {
             try write(to: fileURL, options: .atomic)
         }
     }
 }
 //test
 do {
     let dir: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last! as URL
     let url = dir.appendingPathComponent("logFile.txt")
     try "Test (Date())".appendLineToURL(fileURL: url as URL)
     let result = try String(contentsOf: url as URL, encoding: String.Encoding.utf8)
 }
 catch {
     print("Could not write to file")
 }

感谢 PointZeroTwo.

Thanks PointZeroTwo.

这篇关于在 Swift 中将文本或数据附加到文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆