在swift 2中将新字符串追加到txt文件 [英] Append new string to txt file in swift 2

查看:220
本文介绍了在swift 2中将新字符串追加到txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经用Java进行编码,但是现在我想使用Swift 2将应用程序移至iOS. 因此,我想要一种将新行中的文本追加到应用程序文档中现有txt文件中的方法.

I used to do coding in java but now I want to move my app to iOS using swift 2. So I want a method to append text in new line to an existing txt file in app documents.

我搜索并尝试了许多方法,但是所有方法都覆盖了新的txt文件

I searched and tried so many methods but its all overwriting to new txt file

在Java中,我使用了此方法

In java i used this method

PrintWriter out=null;
        try {
            out=new PrintWriter(new FileWriter("file.txt",true));

                    out.println("some txt"}


                out.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

推荐答案

我认为您必须使用 NSFileHandle :

  let dir:NSURL = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.CachesDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last as NSURL
  let fileurl =  dir.URLByAppendingPathComponent("file.txt")

  let string = "\(NSDate())\n"
  let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

  if NSFileManager.defaultManager().fileExistsAtPath(fileurl.path!) {
        var error:NSError?
        if let fileHandle = NSFileHandle(forWritingToURL: fileurl, error: &error) {
            fileHandle.seekToEndOfFile()
            fileHandle.writeData(data)
            fileHandle.closeFile()
        }
        else {
            println("Can't open fileHandle \(error)")
        }
  }
  else {
        var error:NSError?
        if !data.writeToURL(fileurl, options: .DataWritingAtomic, error: &error) {
            println("Can't write \(error)")
        }
  }

这篇关于在swift 2中将新字符串追加到txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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