Read and write a String from text file

前端 未结 21 1445
别跟我提以往
别跟我提以往 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:49

    To avoid confusion and add ease, I have created two functions for reading and writing strings to files in the documents directory. Here are the functions:

    func writeToDocumentsFile(fileName:String,value:String) {
        let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString
        let path = documentsPath.stringByAppendingPathComponent(fileName)
        var error:NSError?
        value.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: &error)
    }
    
    func readFromDocumentsFile(fileName:String) -> String {
        let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString
        let path = documentsPath.stringByAppendingPathComponent(fileName)
        var checkValidation = NSFileManager.defaultManager()
        var error:NSError?
        var file:String
    
        if checkValidation.fileExistsAtPath(path) {
            file = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as! String
        } else {
            file = "*ERROR* \(fileName) does not exist."
        }
    
        return file
    }
    

    Here is an example of their use:

    writeToDocumentsFile("MyText.txt","Hello world!")
    
    let value = readFromDocumentsFile("MyText.txt")
    println(value)  //Would output 'Hello world!'
    
    let otherValue = readFromDocumentsFile("SomeText.txt")
    println(otherValue)  //Would output '*ERROR* SomeText.txt does not exist.'
    

    Hope this helps!

    Xcode Version: 6.3.2

提交回复
热议问题