简体   繁体   中英

Swift : Reading and Writing to file

Using this solution works, but if I open the file there's no text in it. Am I missing anything?

    let dirs : [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
    if ((dirs) != nil) {
        let dir = dirs![0]; //documents directory
        let path = dir.stringByAppendingPathComponent("data.txt");
        let text = "some text"

        //writing
        text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);

        //reading
        let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
        println(text2)

You should use file manager to get your Document folder url. It doesn't return an optional. Then you can force unwrap the path safely from it and append your path component (file name). You can also use .first or .last to access the first or the last element of your array. You should also consider using atomically = true to prevent data corruption in case of a power failure.

let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as NSURL
let path = documentsUrl.path!.stringByAppendingPathComponent("data.txt")

let text = "some text"

text.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: nil)
if  let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil){
    println(text2)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM