Skip to content
Tutorials Center
My learning

Topics

Lesson 96 of 146 Β· Standard Library and Foundation

Files and Directories

Read and write files in Swift with URL, FileManager and FileHandle - temp directories, listing folders, copying, moving, deleting, partial reads, CSV parsing and CocoaError handling.

Almost every real program touches the disk: it loads a configuration file, writes a log, exports a report or caches a download. Swift's standard library has no file API of its own, because files belong to the operating system, so you use Foundation. Three types do nearly all the work: URL names a file or folder, FileManager creates, lists, copies, moves and deletes things, and FileHandle reads and writes a file in pieces.

This lesson builds up from "write a string to a file" to walking directory trees, appending to logs and handling the errors that file code must expect. It assumes you know errors (nearly every call here throws) and strings. Bytes and binary data get their own lesson next, Data and Bytes.

On this site your program runs in a throwaway sandbox. It may use its temporary directory, but everything it creates vanishes when the run ends, and there are no interesting files to read. That is also a good habit for examples and tests: create a uniquely named temporary folder, work inside it and delete it at the end. Every example below does exactly that.

URL: the name of a file

A URL is not only for web addresses. URL(fileURLWithPath:) makes a URL that points at a path on disk, and it has methods for the usual path chores, so you do not splice strings with "/" by hand.

Swift Building and taking apart file URLs

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

path is the plain path string, lastPathComponent is summary.final.txt, and pathExtension is only the part after the last dot, txt. Removing the extension leaves summary.final. absoluteString is the file:// form, which is what you get when you print a file URL. Use url.path whenever an API wants a path string, such as fileExists(atPath:).

Prefer URL to String for paths. A URL knows whether it names a directory, copes with a missing or doubled slash and cannot be confused with ordinary text.

Writing and reading a whole file

For small files, String and Data can write and read themselves in one call. Here is the complete round trip, inside a temporary folder that cleans up after itself.

Swift Write a file and read it back

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The text has 26 characters and two lines, and because it is plain ASCII the Data has the same 26 bytes. Four things deserve attention.

  • FileManager.default.temporaryDirectory is a writable scratch folder. A UUID in the name makes it unique, so two runs never collide.
  • defer removes the folder when the surrounding scope ends, even if a later line throws. See defer and cleanup.
  • atomically: true writes to a hidden temporary file and renames it into place. Readers see either the old complete file or the new complete file, never half of it. Use it for anything that matters.
  • String(contentsOf:encoding:) loads the whole file into memory. That is perfect for configuration and small data, and wrong for a multi-gigabyte log.

FileManager: folders, copies and walks

FileManager.default is the shared object for working with the file system. The next program builds a small tree, inspects it, copies, moves and deletes files, and lists the result. Directory listings come back in no guaranteed order, so the code sorts before printing.

Swift Create, list, copy, move and delete

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Read the output from the top.

  1. createDirectory(... withIntermediateDirectories: true) builds docs and docs/archive in one call, and does not complain if they already exist.
  2. fileExists(atPath:isDirectory:) is an old Objective-C style API: it fills an ObjCBool that you read through .boolValue. The first line prints true true (exists, is a directory), the second true false (exists, is a file).
  3. The first listing is ["a.txt", "docs"]. contentsOfDirectory is shallow and does not descend.
  4. The enumerator walks the whole tree. It yields Any, which is why the loop uses for case let url as URL. Asking for isDirectoryKey and fileSizeKey up front lets the system fetch them efficiently, and the report shows a.txt (5 bytes), docs/, docs/archive/, docs/archive/c.log (5 bytes) and docs/b.txt (9 bytes).
  5. After copying a.txt, moving the copy into docs and deleting the original, the top folder holds only ["docs"], and docs holds ["a-moved.txt", "archive", "b.txt"].

copyItem and moveItem fail if the destination already exists; delete it first or pick another name. removeItem deletes a folder and everything inside it with no confirmation and no trash, so be careful what path you give it.

FileHandle: reading and writing in pieces

When a file is large, or you want to append without rewriting everything, open a FileHandle. It keeps a current offset, like a cursor, and reads or writes from there.

Swift Append, seek and partial reads with FileHandle

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The file starts as one, and the writer appends two and three after seeking to the end, so it holds one\ntwo\nthree\n. The reader pulls the first four bytes (one plus the newline) and the offset is now 4. After seek(toOffset: 8) it skips two\n and readToEnd() returns three\n. Once at the end, read(upToCount:) returns nil, which is how you detect the end of a file.

Remember to close() handles that you open; the throwing methods shown here (write(contentsOf:), read(upToCount:), seek(toOffset:)) replace the older ones that crashed the process on an I/O error. The last two lines show the standard streams are file handles too: FileHandle.standardError and .standardOutput. In this site's runner stdout and stderr both appear, and stderr is labelled separately.

Do not use the old Objective-C era methods write(_:) and readData(ofLength:) in new code. They raise an exception that Swift cannot catch when the disk is full or the handle is closed. Use the write(contentsOf:) and read(upToCount:) family, which throw ordinary Swift errors.

When file code fails

Files are the part of a program that fails for reasons you do not control: the file is missing, the disk is full, permissions forbid it, another process holds it. Swift forces you to face that, and the compiler will not let you forget:

Swift Forgetting try (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

TEXT
main.swift:4:12: error: call can throw but is not marked with 'try'

The fix is try, inside a do/catch or a throwing function. File errors arrive as CocoaError values (on Linux too), and the code tells you what went wrong:

Swift Handling CocoaError

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Reading a missing file gives the code 260 (.fileReadNoSuchFile), with the message "The operation could not be completed. The file doesn’t exist." Deleting a missing path gives a different code, .fileNoSuchFile, which the second catch matches with a where clause so that one specific problem is handled and every other error still propagates. The last two lines show a second kind of failure, bad content: the bytes FF FE 41 are not valid UTF-8, so String(data:encoding:) returns nil, while String(decoding:as:) repairs the damage by inserting the replacement character and prints οΏ½οΏ½A. Pick the strict one when corrupt data should be an error.

Do not check fileExists first and then open the file. Between the check and the open, another process can delete it. Just try the operation and handle the error.

Processing a file line by line

A typical job is to read a text file, parse each line and skip the lines that do not fit. The program below writes a small CSV file, then totals sales per region and counts the broken row.

Swift Parsing a CSV file

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

North sells 10 Γ— 2.50 plus 6 Γ— 2.50 for 40.00, south 4 Γ— 10.00 for 40.00, east 3 Γ— 7.25 for 21.75. The west row has x where a number belongs, so Int("x") is nil, the guard fails, and skipped becomes 1. The dictionary keys are sorted before printing because a dictionary has no stable order (see dictionaries). Splitting on commas is fine for simple data; real CSV with quoted commas needs a proper parser.

For big files, do not load everything: read with a FileHandle in chunks, or on Apple platforms use the asynchronous url.lines. That property is not available in the Linux Foundation used here, so chunked reading is the portable choice.

Practical rules

  • Build paths with URL, not string concatenation.
  • Write important files with atomically: true.
  • Use unique temporary folders for scratch work and delete them with defer.
  • Never assume a directory listing is sorted; sort what you print or compare.
  • Handle CocoaError codes you can react to and let the rest propagate.
  • Real applications on Apple platforms use the user's Documents or Application Support folders through FileManager.urls(for:in:). In this sandbox those folders are not meaningful, so stay with the temporary directory.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does write(to:atomically: true, encoding:) guarantee?

    Atomic writes go to a temporary file first and are then renamed over the destination.
  2. 2. Which call returns the contents of a folder AND everything in its subfolders?

    contentsOfDirectory is shallow; the enumerator walks the whole tree.
  3. 3. What does FileHandle.read(upToCount:) return when the handle is already at the end of the file?

    nil signals the end of the file, so a loop can stop when it sees it.
  4. 4. Why is it a bad idea to call fileExists(atPath:) and then open the file if it exists?

    Try the operation directly and handle the thrown CocoaError.
  5. 5. What is the difference between String(data:encoding: .utf8) and String(decoding:as: UTF8.self) for invalid bytes?

    Use the failable one when invalid data should be an error, the repairing one when you only want to display something.

Summary

  • URL(fileURLWithPath:) names a file; use appendingPathComponent, lastPathComponent and pathExtension instead of string surgery.
  • String.write(to:atomically:encoding:), String(contentsOf:encoding:) and Data(contentsOf:) handle small files in one call; they load everything into memory.
  • FileManager.default creates folders, lists them (contentsOfDirectory, enumerator), copies, moves and removes items; listing order is not guaranteed.
  • FileHandle reads and writes in pieces with an offset: seekToEnd, write(contentsOf:), read(upToCount:), readToEnd, close.
  • File calls throw CocoaError values; match .code for the cases you can handle, and do not pre-check with fileExists.
  • Examples and tests should work in a unique temporary folder and clean up with defer.

Next: Data and Bytes shows how to work with raw bytes, Base64 and hexadecimal.