Read and write a String from text file

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

    New simpler and recommended method: Apple recommends using URLs for filehandling and the other solutions here seem deprecated (see comments below). The following is the new simple way of reading and writing with URL's (don't forget to handle the possible URL errors):

    Swift 5+, 4 and 3.1

    import Foundation  // Needed for those pasting into Playground
    
    let fileName = "Test"
    let dir = try? FileManager.default.url(for: .documentDirectory, 
          in: .userDomainMask, appropriateFor: nil, create: true)
    
    // If the directory was found, we write a file to it and read it back
    if let fileURL = dir?.appendingPathComponent(fileName).appendingPathExtension("txt") {
    
        // Write to the file named Test
        let outString = "Write this text to the file"
        do {
            try outString.write(to: fileURL, atomically: true, encoding: .utf8)
        } catch {
            print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
        }
    
        // Then reading it back from the file
        var inString = ""
        do {
            inString = try String(contentsOf: fileURL)
        } catch {
            print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
        }
        print("Read from the file: \(inString)")
    }
    

提交回复
热议问题