By Jorge Vega Sánchez


2014-06-07 13:42:17 8 Comments

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 know how to write or read data.

import Cocoa

class DataImporter
{
    /*
    DataImporter is a class to import data from an external file.
    The class is assumed to take a non-trivial amount of time to initialize.
    */
    var fileName = "data.txt"
    // the DataImporter class would provide data importing functionality here
}

class DataManager
{
    @lazy var importer = DataImporter()
    var data = String[]()
    // the DataManager class would provide data management functionality here
}

let manager = DataManager()
manager.data += "Some data"
manager.data += "Some more data"
// the DataImporter instance for the importer property has not yet been created”

println(manager.importer.fileName)
// the DataImporter instance for the importer property has now been created
// prints "data.txt”



var str = "Hello World in Swift Language."

19 comments

@wottpal 2014-06-07 14:12:41

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 String

println(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)

@alttag 2014-10-23 20:50:15

For iOS projects, "stringWithContentsOfFile" is unavailable (deprecated as of iOS 7)

@Leo Dabus 2014-10-24 18:54:31

Nothing to do with iOS projets, it is deprecated and doesn't work anymore with Xcode 6.1 (including Mac OS X )

@shim 2014-11-09 04:34:13

you can use String(contentsOfFile: ...)

@Crashalot 2016-09-24 07:59:12

This no longer compiles on Xcode 8, Swift 3

@Timeless 2017-02-03 03:17:21

similar solution use bundle with iOS 10 Swift 3 here

@Szuwar_Jr 2019-02-11 12:41:07

Earlier solutions answers question, but in my case deleting old content of file while writing was a problem.

So, I created piece of code for writing to file in documents directory without deleting previous content. You probably need better error handling, but I believe it's good starting point. Swift 4. Usuage:

    let filename = "test.txt"
    createOrOverwriteEmptyFileInDocuments(filename: filename)
    if let handle = getHandleForFileInDocuments(filename: filename) {
        writeString(string: "aaa", fileHandle: handle)
        writeString(string: "bbb", fileHandle: handle)
        writeString(string: "\n", fileHandle: handle)
        writeString(string: "ccc", fileHandle: handle)
    }

Helper methods:

func createOrOverwriteEmptyFileInDocuments(filename: String){
    guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
        debugPrint("ERROR IN createOrOverwriteEmptyFileInDocuments")
        return
    }
    let fileURL = dir.appendingPathComponent(filename)
    do {
        try "".write(to: fileURL, atomically: true, encoding: .utf8)
    }
    catch {
        debugPrint("ERROR WRITING STRING: " + error.localizedDescription)
    }
    debugPrint("FILE CREATED: " + fileURL.absoluteString)
}

private func writeString(string: String, fileHandle: FileHandle){
    let data = string.data(using: String.Encoding.utf8)
    guard let dataU = data else {
        debugPrint("ERROR WRITING STRING: " + string)
        return
    }
    fileHandle.seekToEndOfFile()
    fileHandle.write(dataU)
}

private func getHandleForFileInDocuments(filename: String)->FileHandle?{
    guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
        debugPrint("ERROR OPENING FILE")
        return nil
    }
    let fileURL = dir.appendingPathComponent(filename)
    do {
        let fileHandle: FileHandle? = try FileHandle(forWritingTo: fileURL)
        return fileHandle
    }
    catch {
        debugPrint("ERROR OPENING FILE: " + error.localizedDescription)
        return nil
    }
}

@Leo Dabus 2014-10-25 00:06:19

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

@whitneyland 2014-10-28 21:51:14

clean, compiles

@Darvydas 2015-11-17 15:53:52

What is most common mistakes of "There is no such file." Because i added my .txt files to project navigator and then i try to open them i get this message. (Create them on desktop and dragged them to project navigator)

@Adam 2014-06-07 14:18:52

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 and Swift 4.0

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

@Matt Frear 2014-10-26 21:43:36

let text2 = String.stringWithContentsOfFile(path) // XCode 6.0

@Nuno Gonçalves 2014-11-08 16:20:43

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

@zbz.lvlv 2014-12-06 06:54:01

@Adam What is this file at let path = dir.stringByAppendingPathComponent(file);?

@Adam 2014-12-08 12:09:48

@zbz.lvlv It's the name of the file.

@Sashi 2015-04-23 18:42:24

@Adam : using .writeToFile overrides the content of the file, is it possible to append a string to already existing content of the file ?

@Crashalot 2015-07-22 20:03:23

Why did you set atomically to false in writeToFile?

@Adam 2015-07-23 07:50:54

@Sashi If you want to append string to a file you can do the following: read the file to string, append your string and write it back to the original location. Not the most efficient but it will work.

@Adam 2015-07-23 08:17:55

@Crashalot You decide if you need the write to be atomic or not. It depends on your implementation. There is no rule of thumb here. See NSString Class Reference for more details.

@fnc12 2015-08-22 11:59:42

casting as? [String] is not necessary in Swift 2.0

@Maciej Kozieł 2015-11-05 20:38:44

Just a minor upgrade for Swift 2.0. You can use let text2 = try? NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) , if you don't do anything in catch. If you want to just return nil, it's clearer solution. developer.apple.com/library/prerelease/ios/documentation/Swi‌​ft/…

@user3325915 2016-04-16 22:28:34

This should be removed, code does not work for new versions of Swift.

@Adam 2016-04-17 06:53:50

@Yusha Just checked with the newest version of Xcode (7.3) and it is working perfectly.

@cpu_meltdown 2016-08-02 13:08:37

@Adam do you know how to access the files after you write something to it? I am writing a simple app where I want to save strings to a file on daily bases, so how can I get that file afterwards?

@Adam 2016-08-03 13:50:34

@billy_b29 The code after this line: //reading does exactly that.

@AthanasiusOfAlex 2016-09-27 12:33:01

In Swift 3.0, you can remove most of the "NS" prefixes if you want: e.g., let text2 = try String(contentsOf: path, encoding: String.Encoding.utf8).

@Abo3atef 2017-03-26 10:54:33

Thanks So Much :) You saved a lot of time :)

@Van Du Tran 2017-05-01 14:48:15

Is there a "filestream.close()" to call? Sometimes, after the program runs, the file is not written to the hard drive.. I wonder why.

@user1258202 2017-07-12 11:51:20

Why do I get "No calls to throwing functions occur within 'try' expression" warning next to the "try text.write..." line? I'm using Swift 3.0 & Xcode 8.2.1

@Suhaib 2018-02-13 15:15:18

I think it would be better if you arrange the code to have the swift 4 at top :-p.

@Mike Irving 2019-06-25 15:42:35

Delete Handler is also useful do { try FileManager.default.removeItem(at: fileURL) } catch {/* error handling here */}

@iosMentalist 2018-09-06 12:09:36

Simplest way to read a file in Swift > 4.0

 let path = Bundle.main.path(forResource: "data", ofType: "txt") // file path for file "data.txt"
        do {
            var text = try String(contentsOfFile: path!)
        }
        catch(_){print("error")}
    }

@Hannes Sverrisson 2016-02-13 01:04:48

New simpler and recommended method: Apple recommends using URL for filehandling and the above solutions 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 4.0 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)")
}

@Andrej 2016-04-08 15:58:44

Can you provide a reference where Apple recommends such way. Or can you elaborate a little more on why is this the recommended way?

@Hannes Sverrisson 2016-04-09 00:35:03

@Andrej "URL objects are the preferred way to refer to local files. Most objects that read data from or write data to a file have methods that accept an NSURL object instead of a pathname as the file reference." developer.apple.com/library/ios/documentation/Cocoa/Referenc‌​e/…

@cuomo456 2016-11-18 00:36:32

You don't have to cast the errors as NSError, or even use "catch let error." You can just do catch and you get the error variable for free.

@Hannes Sverrisson 2016-11-18 10:09:34

@cuomo456 your right I remove it, it's a leftover from previous Swift beta.

@Paul Martz 2017-11-02 21:08:41

Probably the most useful answer on this page (there's a joke here somewhere - how many engineers does it take to write Swift code to do text file I/O?). But I do have a question. Am I to assume that the only way to write a text file is to create one humungous String and do a single write()? Because if I try to write multiple Strings to the same URL, the result is that the file contains only the last String written.

@Hannes Sverrisson 2017-11-03 09:16:45

@user1593861 This is the simplest method when you already have a string and it's not extremely large. The write is done asynchronously. If you have a humungous string then you can write to file using Streams, but it is beyond this answer, see further stackoverflow.com/questions/36120854/… . Thanks for the nice comment :)

@Hannes Sverrisson 2018-04-15 16:01:59

@Alshcompiler The create: true informs FileManager to create the directory if it's not already there, instead of failing

@biggreentree 2018-12-03 22:20:37

hi all, tried tis code but I cannot solve my issue, could you help me here: stackoverflow.com/questions/53598917/…

@Birju 2019-06-21 12:09:18

If i want to read data from .docx file then how will it be possible?

@Hannes Sverrisson 2019-06-21 14:03:36

@Birju DOCX is a zipped XML file so you would open it and parse the XML. But the details to do it are way beyond a comment.

@Birju 2019-06-24 04:37:36

@HannesSverrisson , thank you for your reply. Can you give me any code stuff or example that how to do it actually ?. Because i am stuck to convert .docx to text.

@Hannes Sverrisson 2019-06-25 09:11:13

@Birju Thats a lot of work, but if you send me a file I can make a code for you.

@A. K. M. Tariqul Islam 2016-05-29 05:54:45

I want to show you only the first part, that is read. Here's how simply you can read:

Swift 3:

let s = try String(contentsOfFile: Bundle.main.path(forResource: "myFile", ofType: "txt")!)

Swift 2:

let s = try! String(contentsOfFile: NSBundle.mainBundle().pathForResource("myFile", ofType: "txt")!)

@oOEric 2017-02-11 14:12:24

remember to add: do { ..code above..} catch { }

@Prashant Gaikwad 2017-09-27 05:09:28

Xcode 8.3.2 Swift 3.x. Using NSKeyedArchiver and NSKeyedUnarchiver

Reading file from documents

let documentsDirectoryPathString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let documentsDirectoryPath = NSURL(string: documentsDirectoryPathString)!
let jsonFilePath = documentsDirectoryPath.appendingPathComponent("Filename.json")

let fileManager = FileManager.default
var isDirectory: ObjCBool = false

if fileManager.fileExists(atPath: (jsonFilePath?.absoluteString)!, isDirectory: &isDirectory) {

let finalDataDict = NSKeyedUnarchiver.unarchiveObject(withFile: (jsonFilePath?.absoluteString)!) as! [String: Any]
}
else{
     print("File does not exists")
}

Write file to documents

NSKeyedArchiver.archiveRootObject(finalDataDict, toFile:(jsonFilePath?.absoluteString)!)

@Adam Dingle 2017-05-18 18:04:44

This works with Swift 3.1.1 on Linux:

import Foundation

let s = try! String(contentsOfFile: "yo", encoding: .utf8)

@GangiReddy Rami Reddy 2017-03-26 07:29:23

Latest swift3 code
You can read data from text file just use bellow code This my text file

     {
"NumberOfSlices": "8",
"NrScenes": "5",
"Scenes": [{
           "dataType": "label1",
           "image":"http://is3.mzstatic.com/image/thumb/Purple19/v4/6e/81/31/6e8131cf-2092-3cd3-534c-28e129897ca9/mzl.syvaewyp.png/53x53bb-85.png",

           "value": "Hello",
           "color": "(UIColor.red)"
           }, {
           "dataType": "label2",
           "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png",
           "value": "Hi There",
           "color": "(UIColor.blue)"
           }, {
           "dataType": "label3",
           "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png",

           "value": "hi how r u ",
           "color": "(UIColor.green)"
           }, {
           "dataType": "label4",
           "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png",
           "value": "what are u doing  ",
           "color": "(UIColor.purple)"
           }, {
           "dataType": "label5",
          "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png",
           "value": "how many times ",
           "color": "(UIColor.white)"
           }, {
           "dataType": "label6",
           "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/5a/f3/06/5af306b0-7cac-1808-f440-bab7a0d18ec0/mzl.towjvmpm.png/53x53bb-85.png",
           "value": "hi how r u ",
           "color": "(UIColor.blue)"
           }, {
           "dataType": "label7",
           "image":"http://is5.mzstatic.com/image/thumb/Purple71/v4/a8/dc/eb/a8dceb29-6daf-ca0f-d037-df9f34cdc476/mzl.ukhhsxik.png/53x53bb-85.png",
           "value": "hi how r u ",
           "color": "(UIColor.gry)"
           }, {
           "dataType": "label8",
           "image":"http://is2.mzstatic.com/image/thumb/Purple71/v4/15/23/e0/1523e03c-fff2-291e-80a7-73f35d45c7e5/mzl.zejcvahm.png/53x53bb-85.png",
           "value": "hi how r u ",
           "color": "(UIColor.brown)"
           }]

}

You can use this code you get data from text json file in swift3

     let filePath = Bundle.main.path(forResource: "nameoftheyourjsonTextfile", ofType: "json")


    let contentData = FileManager.default.contents(atPath: filePath!)
    let content = NSString(data: contentData!, encoding: String.Encoding.utf8.rawValue) as? String

    print(content)
    let json = try! JSONSerialization.jsonObject(with: contentData!) as! NSDictionary
    print(json)
    let app = json.object(forKey: "Scenes") as! NSArray!
    let _ : NSDictionary
    for dict in app! {
        let colorNam = (dict as AnyObject).object(forKey: "color") as! String
        print("colors are \(colorNam)")

       // let colour = UIColor(hexString: colorNam) {
       // colorsArray.append(colour.cgColor)
       // colorsArray.append(colorNam  as! UIColor)

        let value = (dict as AnyObject).object(forKey: "value") as! String
        print("the values are \(value)")
        valuesArray.append(value)

        let images = (dict as AnyObject).object(forKey: "image") as! String
        let url = URL(string: images as String)
        let data = try? Data(contentsOf: url!)
        print(data)
        let image1 = UIImage(data: data!)! as UIImage
        imagesArray.append(image1)
         print(image1)
            }

@maroc 2017-02-19 21:45:21

 func writeToDocumentsFile(fileName:String,value:String) {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
    let path = documentsPath.appendingPathComponent(fileName)
    do{
    try value.write(toFile: path, atomically: true, encoding: String.Encoding.utf8)
}catch{
    }
    }

func readFromDocumentsFile(fileName:String) -> String {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
    let path = documentsPath.appendingPathComponent(fileName)
    let checkValidation = FileManager.default
    var file:String

    if checkValidation.fileExists(atPath: path) {
        do{
       try file = NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String
        }catch{
            file = ""
        }
        } else {
        file = ""
    }

    return file
}

@Crashalot 2016-09-24 08:00:38

Xcode 8, Swift 3 way to read file from the app bundle:

if let path = Bundle.main.path(forResource: filename, ofType: nil) {
    do {
        let text = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
        print(text)
    } catch {
        printError("Failed to read text from \(filename)")
    }
} else {
    printError("Failed to load file from app bundle \(filename)")
} 

Here's a convenient copy and paste Extension

public extension String {
    func contentsOrBlank()->String {
        if let path = Bundle.main.path(forResource:self , ofType: nil) {
            do {
                let text = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
                return text
                } catch { print("Failed to read text from bundle file \(self)") }
        } else { print("Failed to load file from bundle \(self)") }
        return ""
    }
    }

For example

let t = "yourFile.txt".contentsOrBlank()

You almost always want an array of lines:

let r:[String] = "yourFile.txt"
     .contentsOrBlank()
     .characters
     .split(separator: "\n", omittingEmptySubsequences:ignore)
     .map(String.init)

@Fattie 2016-12-21 14:11:04

I pasted in a handy extension @crashalot - feel free to delete, cheers

@Fattie 2016-12-23 15:26:39

sent bounty to thank fantastic answer, cheers @crashalot

@Alsh compiler 2018-04-15 13:19:37

THIS IS THE ONLY WORKING ANSWER O:)

@Hannes Sverrisson 2018-04-15 16:15:04

@Alshcompiler NO! You can't WRITE a file into the bundle.

@Alsh compiler 2018-04-15 23:05:36

I was talking about reading from file, it's the only answer that worked with me if the file is in project files

@indago 2019-06-17 08:08:08

@Crashalot can this code read a file in a USB drive? Swift

@gooroo7 2015-06-06 17:42:58

To avoid confusion and add ease, I have created two functions for reading and writing strings to files in the documents directory. Here are the functions:

func writeToDocumentsFile(fileName:String,value:String) {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString
    let path = documentsPath.stringByAppendingPathComponent(fileName)
    var error:NSError?
    value.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: &error)
}

func readFromDocumentsFile(fileName:String) -> String {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString
    let path = documentsPath.stringByAppendingPathComponent(fileName)
    var checkValidation = NSFileManager.defaultManager()
    var error:NSError?
    var file:String

    if checkValidation.fileExistsAtPath(path) {
        file = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as! String
    } else {
        file = "*ERROR* \(fileName) does not exist."
    }

    return file
}

Here is an example of their use:

writeToDocumentsFile("MyText.txt","Hello world!")

let value = readFromDocumentsFile("MyText.txt")
println(value)  //Would output 'Hello world!'

let otherValue = readFromDocumentsFile("SomeText.txt")
println(otherValue)  //Would output '*ERROR* SomeText.txt does not exist.'

Hope this helps!

Xcode Version: 6.3.2

@simon 2016-04-13 15:03:07

In Xcode 7.3 the functions do not compile.

@Alessandro Mattiuzzi 2016-06-28 07:41:01

For my txt file works this way:

let myFileURL = NSBundle.mainBundle().URLForResource("listacomuni", withExtension: "txt")!
let myText = try! String(contentsOfURL: myFileURL, encoding: NSISOLatin1StringEncoding)
print(String(myText))

@Sam Allen 2016-04-22 20:43:58

In the function example, (read|write)DocumentsFromFile(...) having some function wrappers certainly seems to makes sense since everything in OSx and iOS seems to need three or four major classes instantiated and a bunch of properties, configured, linked, instantiated, and set, just to write "Hi" to a file, in 182 countries.

However, these examples aren't complete enough to use in a real program. The write function does not report any errors creating or writing to the file. On the read, I don't think it's a good idea to return an error that the file doesn't exist as the string that is supposed to contain the data that was read. You would want to know that it failed and why, through some notification mechanism, like an exception. Then, you can write some code that outputs what the problem is and allows the user to correct it, or "correctly" breaks the program at that point.

You would not want to just return a string with an "Error file does not exist" in it. Then, you would have to look for the error in the string from calling function each time and handle it there. You also possibly couldn't really tell if the error string was actually read from an actual file, or if it was produced from your code.

You can't even call the read like this in swift 2.2 and Xcode 7.3 because NSString(contentsOfFile...) throws an exception. It is a compile time error if you do not have any code to catch it and do something with it, like print it to stdout, or better, an error popup window, or stderr. I have heard that Apple is moving away from try catch and exceptions, but it's going to be a long move and it's not possible to write code without this. I don't know where the &error argument comes from, perhaps an older version, but NSString.writeTo[File|URL] does not currently have an NSError argument. They are defined like this in NSString.h :

public func writeToURL(url: NSURL, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws
public func writeToFile(path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws
public convenience init(contentsOfURL url: NSURL, encoding enc: UInt) throws
public convenience init(contentsOfFile path: String, encoding enc: UInt) throws

Also, the file not existing is just one of a number of potential problems your program might have reading a file, such as a permissions problem, the file size, or numerous other issues that you would not even want to try to code a handler for each one of them. It's best to just assume it's all correct and catch and print, or handle, an exception if something goes amiss, besides, at this point, you don't really have a choice anyway.

Here are my rewrites :

func writeToDocumentsFile(fileName:String,value:String) {

    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString!
    let path = documentsPath.stringByAppendingPathComponent(fileName)

    do {
        try value.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding)
    } catch let error as NSError {
        print("ERROR : writing to file \(path) : \(error.localizedDescription)")
    }

}

func readFromDocumentsFile(fileName:String) -> String {

    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
    let path = documentsPath.stringByAppendingPathComponent(fileName)

    var readText : String = ""

    do {
        try readText = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String
    }
    catch let error as NSError {
        print("ERROR : reading from file \(fileName) : \(error.localizedDescription)")
    }
    return readText
}

@Sam Allen 2017-10-17 14:32:37

In many of your responses I think you're not grasping my point. ( or you may not care and that's ok ). However, to be clear, throwing an exception, and handling it somehow when you are looking for a file that's not there ( or has another issue such as a permission ) is far better than returning a string such as "ERROR: File [filename] does not exist" as the string you were supposed to actually read from the file. Then just printing that. If anything you should print the exception details, not the failed to be read string that now has an error in it.The program probably shouldn't just continue.

@Nagarjun 2016-02-22 06:56:15

I had to recode like this:

let path = NSBundle.mainBundle().pathForResource("Output_5", ofType: "xml")
let text = try? NSString(contentsOfFile: path! as String, encoding: NSUTF8StringEncoding)
print(text)

@shoumikhin 2015-07-02 18:16:51

You may find this tool useful to not only read from file in Swift but also parse your input: https://github.com/shoumikhin/StreamScanner

Just specify the file path and data delimiters like this:

import StreamScanner

if let input = NSFileHandle(forReadingAtPath: "/file/path")
{
    let scanner = StreamScanner(source: input, delimiters: NSCharacterSet(charactersInString: ":\n"))  //separate data by colons and newlines

    while let field: String = scanner.read()
    {
        //use field
    }
}

Hope, this helps.

@NRV 2015-01-23 06:11:29

write in ViewDidLoad

var error: NSError?
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var documentsDirectory = paths.first as String
var dataPath = documentsDirectory.stringByAppendingPathComponent("MyFolder")

if !NSFileManager.defaultManager().fileExistsAtPath(dataPath) {
    NSFileManager.defaultManager().createDirectoryAtPath(dataPath, withIntermediateDirectories: false, attributes: nil, error: &error)
} else {
    println("not creted or exist")
}

func listDocumentDirectoryfiles() -> [String] {
    if let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as? String {
        let myFilePath = documentDirectory.stringByAppendingPathComponent("MyFolder")
        return NSFileManager.defaultManager().contentsOfDirectoryAtPath(myFilePath, error: nil) as [String]
    }
    return []
}

@DCorrigan 2014-10-24 16:47:22

The current accepted answer above from Adam had some errors for me but here is how I reworked his answer and made this work for me.

let file = "file.txt"

let dirs: [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]

if (dirs != nil) {
    let directories:[String] = dirs!
    let dirs = directories[0]; //documents directory
    let path = dirs.stringByAppendingPathComponent(file);
    let text = "some text"

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

    //reading
     var error:NSError?

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

    if let theError = error {
        print("\(theError.localizedDescription)")
    }
}

Related Questions

Sponsored Content

30 Answered Questions

[SOLVED] How do I create a file and write to it in Java?

  • 2010-05-21 19:58:55
  • Drew Johnson
  • 2719107 View
  • 1300 Score
  • 30 Answer
  • Tags:   java file-io

10 Answered Questions

[SOLVED] Delete a file or folder

23 Answered Questions

[SOLVED] Find and restore a deleted file in a Git repository

12 Answered Questions

[SOLVED] Correct way to write line to file?

  • 2011-05-28 05:44:53
  • Yaroslav Bulatov
  • 1886799 View
  • 943 Score
  • 12 Answer
  • Tags:   python file-io

42 Answered Questions

[SOLVED] How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

  • 2008-09-29 22:30:28
  • mistrmark
  • 1020363 View
  • 1767 Score
  • 42 Answer
  • Tags:   c# .net excel file-io

33 Answered Questions

[SOLVED] How do I create a Java string from the contents of a file?

18 Answered Questions

[SOLVED] How do I tell if a regular file does not exist in Bash?

  • 2009-03-12 14:48:43
  • Bill the Lizard
  • 2358182 View
  • 2995 Score
  • 18 Answer
  • Tags:   bash file-io scripting

26 Answered Questions

[SOLVED] Find all files in a directory with extension .txt in Python

  • 2010-10-19 01:09:13
  • usertest
  • 1471699 View
  • 1043 Score
  • 26 Answer
  • Tags:   python file-io

21 Answered Questions

[SOLVED] How to read a large text file line by line using Java?

25 Answered Questions

[SOLVED] Reading a plain text file in Java

  • 2011-01-17 18:29:13
  • Tim the Enchanter
  • 2253428 View
  • 884 Score
  • 25 Answer
  • Tags:   java file-io ascii

Sponsored Content