Read and write a String from text file Read and write a String from text file swift swift

Read and write a String from text file


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 itlet text = "some text" //just a textif 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 itlet text = "some text" //just a textif 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)}


Assuming that you have moved your text file data.txt to your Xcode-project (Use drag'n'drop and check "Copy files if necessary") you can do the following just like in Objective-C:

let bundle = NSBundle.mainBundle()let path = bundle.pathForResource("data", ofType: "txt")        let content = NSString.stringWithContentsOfFile(path) as Stringprintln(content) // prints the content of data.txt

Update:
For reading a file from Bundle (iOS) you can use:

let path = NSBundle.mainBundle().pathForResource("FileName", ofType: "txt")var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!println(text)

Update for Swift 3:

let path = Bundle.main.path(forResource: "data", ofType: "txt") // file path for file "data.txt"var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!

For Swift 5

let path = Bundle.main.path(forResource: "ListAlertJson", ofType: "txt") // file path for file "data.txt"let string = try String(contentsOfFile: path!, encoding: String.Encoding.utf8)


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)}