-->

Append new string to txt file in swift 2

2019-06-01 09:59发布

问题:

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.

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

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();
        }

回答1:

I think you must use 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)")
        }
  }


回答2:

You can use the below method to append String to a file

func writeToFile(content: String, fileName: String) {

    let contentToAppend = content+"\n"
    let filePath = NSHomeDirectory() + "/Documents/" + fileName

    //Check if file exists
    if let fileHandle = NSFileHandle(forWritingAtPath: filePath) {
        //Append to file
        fileHandle.seekToEndOfFile()
        fileHandle.writeData(contentToAppend.dataUsingEncoding(NSUTF8StringEncoding)!)
    }
    else {
        //Create new file
        do {
            try contentToAppend.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding)
        } catch {
            print("Error creating \(filePath)")
        }
    }
}