FileManager
The FileManager class in Swift lets you create, check, delete, and move files and directories in the file system.
Method List
| Method / Property | Description |
|---|---|
| FileManager.default | Returns the shared FileManager instance. |
| fileExists(atPath:) | Checks whether a file or directory exists at the specified path. |
| createDirectory(at:withIntermediateDirectories:) | Creates a directory. |
| createFile(atPath:contents:) | Creates a file and writes data to it. |
| contentsOfDirectory(at:includingPropertiesForKeys:) | Returns a list of files in a directory. |
| copyItem(at:to:) | Copies a file or directory. |
| moveItem(at:to:) | Moves a file or directory. |
| removeItem(at:) | Deletes a file or directory. |
| urls(for:in:) | Returns the URL for standard directories such as Documents and Caches. |
Sample Code
import Foundation
let fm = FileManager.default
// Get the URL for the Documents directory
let docsURL = fm.urls(for: .documentDirectory, in: .userDomainMask)[0]
print("Documents: \(docsURL.path)")
// Create and write a file
let fileURL = docsURL.appendingPathComponent("test.txt")
let content = "Hello, Swift FileManager!"
try? content.write(to: fileURL, atomically: true, encoding: .utf8)
// Check if the file exists
print("Exists: \(fm.fileExists(atPath: fileURL.path))")
// Read the file
if let text = try? String(contentsOf: fileURL, encoding: .utf8) {
print("Contents: \(text)")
}
// Create a directory
let dirURL = docsURL.appendingPathComponent("MyFolder")
try? fm.createDirectory(at: dirURL, withIntermediateDirectories: true)
print("Directory created: \(fm.fileExists(atPath: dirURL.path))")
// Copy a file
let copyURL = dirURL.appendingPathComponent("copy.txt")
try? fm.copyItem(at: fileURL, to: copyURL)
// List files in a directory
if let contents = try? fm.contentsOfDirectory(at: docsURL, includingPropertiesForKeys: nil) {
print("Contents of Documents:")
for url in contents {
print(" \(url.lastPathComponent)")
}
}
// Move a file
let movedURL = docsURL.appendingPathComponent("moved.txt")
try? fm.moveItem(at: copyURL, to: movedURL)
// Delete a file
try? fm.removeItem(at: movedURL)
try? fm.removeItem(at: dirURL)
print("Exists after deletion: \(fm.fileExists(atPath: movedURL.path))")
Notes
In iOS and macOS apps, the convention is to store user data in the Documents directory and cache data in the Caches directory. You can retrieve these paths using FileManager.default.urls(for:in:).
For reading and writing files, String.write(to:) and Data.write(to:) are convenient options. Use FileManager for larger files or more complex operations. Always handle file operation errors with try-catch. Operations may temporarily fail depending on the iCloud Drive sync state.
For persisting small amounts of data with UserDefaults, see UserDefaults.
If you find any errors or copyright issues, please contact us.