Basic File I/O in Swift

In this post we learn how to do basic file I/O in Swift. We will create a file and write some text to it. All code here is w.r.t. Swift 5.7.2. First we need to import Foundation:

import Foundation

Then we create a URL:

let fileManager = FileManager.default
let url = URL(fileURLWithPath: filename)
let filePath = url.path        

Now we can create a file:

guard (fileManager.createFile(atPath: filePath, contents:nil)) else {
    throw Errors.fileIOException
}

Next we get a FileHandle:

let file = FileHandle(forWritingAtPath : filename)!

and now we can start writing to the file:

file.write(Data("Hello World\n".utf8))

When you are done, remember to close the file like so:

try file.close()

That’s it! Some tips:

  • You will get an error if you attempt to fetch a FileHandle without creating the file first
  • We see the API is different from what you would expect coming from Java or C#. You don’t create any BufferedStreamWriter.
  • Some code samples write to file using the write method on the String object and passing it a TextOutputStream. Try it if you like and let me know if it works.
This entry was posted in Computers, programming, Software and tagged . Bookmark the permalink.

Leave a comment