Read and write a String from text file

前端 未结 21 1417
别跟我提以往
别跟我提以往 2020-11-22 00:02

I need to read and write data to/from a text file, but I haven\'t been able to figure out how.

I found this sample code in the Swift\'s iBook, but I still don\'t kno

21条回答
  •  爱一瞬间的悲伤
    2020-11-22 00:45

    The current accepted answer above from Adam had some errors for me but here is how I reworked his answer and made this work for me.

    let file = "file.txt"
    
    let dirs: [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
    
    if (dirs != nil) {
        let directories:[String] = dirs!
        let dirs = directories[0]; //documents directory
        let path = dirs.stringByAppendingPathComponent(file);
        let text = "some text"
    
        //writing
        text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
    
        //reading
         var error:NSError?
    
        //reading
        let text2 = String(contentsOfFile: path, encoding:NSUTF8StringEncoding, error: &error)
    
        if let theError = error {
            print("\(theError.localizedDescription)")
        }
    }
    

提交回复
热议问题