【问题标题】:Append CSV or Text File in Swift 2在 Swift 2 中附加 CSV 或文本文件
【发布时间】:2016-08-27 22:47:21
【问题描述】:

我是 Swift 新手,花了几天时间在 stackoverflow 和谷歌上搜索,以找到一个可以在 csv/文本文件中附加数据的工作示例。有几个示例/质量检查,但我无法找到确切的解决方案。最初的问题是系统无法在 iPhone 中找到本地文件。然后我发现创建文件路径并在最后附加值时出错。

【问题讨论】:

    标签: ios file csv swift2 append


    【解决方案1】:

    创建文件名:

    let fileName = "file"
    

    找到文档目录的URL:

    let DocumentDirURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
    

    附加文件名和扩展名以创建绝对文件路径:

    let fileURL = DocumentDirURL.URLByAppendingPathComponent(fileName).URLByAppendingPathExtension("csv")
    

    使用 NSFileHandle 打开文件:

    let file: NSFileHandle? = NSFileHandle(forUpdatingAtPath: fileURL.path!)
    

    在文件末尾写入数据:

    if file == nil {
            NSLog("File open failed")
        } else {
            // assuming data contains contents to be written
            let fileData = data.dataUsingEncoding(NSUTF8StringEncoding)
            // seek to end of the file to append at the end of the file.
            file?.seekToEndOfFile()
            file?.writeData(fileData!)
            file?.closeFile()
        }
    

    【讨论】:

      猜你喜欢
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-21
      • 2014-09-18
      • 2019-11-30
      • 1970-01-01
      相关资源
      最近更新 更多