Read from and Write to a text file in Swift
Reading & writing to a text file in Swift is simple. We use the documents directory to store our text files and read from them. The code below does this.
// Save data to file let fileName = "Test" let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) let fileURL = DocumentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt") print("FilePath: \(fileURL.path)") let writeString = "Write this text to the fileURL as text in iOS using Swift" do { // Write to the file try writeString.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8) } catch let error as NSError { print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription) } var readString = "" // Used to store the file contents do { // Read the file contents readString = try String(contentsOf: fileURL) } catch let error as NSError { print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription) } print("File Text: \(readString)")
The comments explain the code, with what each step does. This will result in the following output, which is what we wrote to the text file in the first place.
FilePath: Optional("/Users/Seemu/Library/Developer/CoreSimulator/Devices/350DA986-1B1A-42BB-8B6E-3F8DF8CE851F/data/Containers/Data/Application/22DE976E-273E-4B58-2E43-7FDC3D43AABD/Documents/Test.txt") File Text: Write this text to the fileURL as text in iOS using Swift
If you have a text file already added to your XCode project like so:
You can read it with the following:
// File location let fileURLProject = Bundle.main.path(forResource: "ProjectTextFile", ofType: "txt") // Read from the file var readStringProject = "" do { readStringProject = try String(contentsOfFile: fileURLProject!, encoding: String.Encoding.utf8) } catch let error as NSError { print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription) } print(readStringProject)
This will give the file output:
This text is in a txt file in our project.
If you want to write to this file, simply adapt the code from the Write to the fileURLProject file instead.