Read and write a String from text file

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

    Xcode 8.x • Swift 3.x or later

    do {
        // get the documents folder url
        if let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            // create the destination url for the text file to be saved
            let fileURL = documentDirectory.appendingPathComponent("file.txt")
            // define the string/text to be saved
            let text = "Hello World !!!"
            // writing to disk 
            // Note: if you set atomically to true it will overwrite the file if it exists without a warning
            try text.write(to: fileURL, atomically: false, encoding: .utf8)
            print("saving was successful")
            // any posterior code goes here
            // reading from disk
            let savedText = try String(contentsOf: fileURL)
            print("savedText:", savedText)   // "Hello World !!!\n"
        }
    } catch {
        print("error:", error)
    }
    

提交回复
热议问题