Read and write a String from text file

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

    For reading and writing you should use a location that is writeable, for example documents directory. The following code shows how to read and write a simple string. You can test it on a playground.

    Swift 3.x - 5.x

    let file = "file.txt" //this is the file. we will write to and read from it
    
    let text = "some text" //just a text
    
    if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
    
        let fileURL = dir.appendingPathComponent(file)
    
        //writing
        do {
            try text.write(to: fileURL, atomically: false, encoding: .utf8)
        }
        catch {/* error handling here */}
    
        //reading
        do {
            let text2 = try String(contentsOf: fileURL, encoding: .utf8)
        }
        catch {/* error handling here */}
    }
    

    Swift 2.2

    let file = "file.txt" //this is the file. we will write to and read from it
    
    let text = "some text" //just a text
    
    if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
        let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)
    
        //writing
        do {
            try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding)
        }
        catch {/* error handling here */}
    
        //reading
        do {
            let text2 = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding)
        }
        catch {/* error handling here */}
    }
    

    Swift 1.x

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

提交回复
热议问题