SwiftSnippetiOS
Last updated at 2023-08-28

Easy Swift Files Operation using FileManager

ClickUp
Note
AI Status
Last Edit By
Last edited time
Aug 28, 2023 10:19 AM
Metatag
Slug
swift-files-operation-filemanager
Writer
Published
Published
Date
Aug 28, 2023
Category
Swift
Snippet
iOS
In Swift, FileManager is a class provided by the Foundation framework that allows you to perform file and directory management tasks.
It provides methods and properties for interacting with the file system, such as creating, copying, moving, and deleting files and directories.
The FileManager class is responsible for abstracting the underlying file system operations, allowing you to work with files and directories in a platform-independent way. It provides a convenient API for managing file operations without directly dealing with low-level file system APIs.
🥸
Jump to Check File if Exists if you want to copy and paste code right away

What Can I Do with the Swift File Manager?

Some common tasks you can perform using FileManager include:
  • Checking if a file or directory exists
  • Creating new files or directories
  • Copying files or directories
  • Moving or renaming files or directories
  • Deleting files or directories
  • Getting attributes of files or directories, such as size, modification date, and permissions
  • Enumerating the contents of a directory

What Will You Learn in This Article?

Similar to Golang Files Tutorial, you will learn how to use FileManager to store user information in user_info.txt.

1. Check if File or Directory is Exists

File

When you need to check if user_info.txt exists, you can use fileExists(atPath:) method.
You can check this reference for Apple official documentation.
func checkIfFileExists() { let fileManager = FileManager.default let filePath = "user_info.txt" if fileManager.fileExists(atPath: filePath) { print("User info file exists") } else { print("User info file does not exist") } }

Directory

A similar method exists to check if a directory exists at a given path using the fileExists(atPath:isDirectory:) method from File Manager.
func checkIsDirectory(_ path: String) -> Bool { let fileManager = FileManager.default var isDirectory: ObjCBool = false if fileManager.fileExists(atPath: path, isDirectory: &isDirectory) { return isDirectory.boolValue } return false } func main() { let path = "/Users/username/Documents" if checkIsDirectory(path) { print("\(path) is a directory.") } else { print("\(path) is a file.") } }

2. Create a New File

When you want to save user data to user_info.txt you can use createFile(atPath:contents:attributes) to create the file before writing.
func createFile() { let fileManager = FileManager.default let filePath = "/User/Documents/user_info.txt" if !fileManager.fileExists(atPath: filePath) { fileManager.createFile(atPath: filePath, contents: nil, attributes: nil) print("User info file created") } }
For official documentation, you can visit createFile documentation.

3. Delete File

Deleting a file is part of a program. Whenever a user wants to remove their information from your database, you can remove the file using removeItem(atPath:).
func deleteFile() { let fileManager = FileManager.default let filePath = "user_info.txt" do { try fileManager.removeItem(atPath: filePath) print("User info file deleted") } catch { print(error.localizedDescription) } }
There is also another method that accepts URL to remove files; you can check how to delete a file in Swift in that article.

4. Get File Size

To check whether you should suggest that users move their data to another form of storage, for example, a Relational Database, you can check the file size first.
You can use the attributesOfItem(atPath:) method like this:
func getFileSize() { let fileManager = FileManager.default let filePath = "user_info.txt" do { let attributes = try fileManager.attributesOfItem(atPath: filePath) if let fileSize = attributes[.size] as? Int64 { print("User info file size: \(fileSize) bytes") } } catch { print(error.localizedDescription) } }
In above usage, you take the file size using .size key and cast the value to Int64.
Check out more information about how to use the method in this documentation.

5. Get File Last Modification

There are many programs that rely on file last modification information. You can also check and implement similar functionality using the attributesOfItem(atPath:) method.
Rather than subscripting using the .size key, you can use the .modificationDate instead.
func getLastModificationTime() { let fileManager = FileManager.default let filePath = "user_info.txt" do { let attributes = try fileManager.attributesOfItem(atPath: filePath) if let modificationDate = attributes[.modificationDate] as? Date { print("Last modified:", modificationDate) } } catch { print(error.localizedDescription) } }

6. Read Content of File

To read the content of a file in Swift, you can use the contents(atPath:) method. This method returns a Data? instance. It will return nil when there is an error or the supplied path is a directory.
func compareFileContents(atPath filePath1: String, andPath filePath2: String) { let fileManager = FileManager.default if let data1 = fileManager.contents(atPath: filePath1), let data2 = fileManager.contents(atPath: filePath2) { if data1 == data2 { print("The contents of \(filePath1) and \(filePath2) are identical.") } else { print("The contents of \(filePath1) and \(filePath2) are different.") } } else { print("One or both files do not exist.") } }

7. Write to a File

Writing to a file can be done using the write method of String or Data.
func writeToFile() { let filePath = "user_info.txt" let content = "name: Jack\nage: 34\nhobby: Fishing\n" do { try content.write(toFile: filePath, atomically: true, encoding: .utf8) print("Done writing") } catch { print(error.localizedDescription) } }

8. Append to a File using FileHandle

You can use FileHandle, which represents IO, to append file content in Swift.
func appendToFile() { let filePath = "user_info.txt" let content = "job: Software Engineer\n" if let fileHandle = FileHandle(forWritingAtPath: filePath) { fileHandle.seekToEndOfFile() if let data = content.data(using: .utf8) { fileHandle.write(data) fileHandle.closeFile() } } }

9. Copying File

You can use copyItem method to copy content of a file to the other using FileManager.
func copyFile(atPath srcPath: String, toPath dstPath: String) { let fileManager = FileManager.default do { try fileManager.copyItem(atPath: srcPath, toPath: dstPath) print("File copied from \(srcPath) to \(dstPath)") } catch { print("Error: \(error.localizedDescription)") } } func main() { let sourceFilePath = "/Users/username/Documents/sourceFile.txt" let destinationFilePath = "/Users/username/Documents/destinationFile.txt" copyFile(atPath: sourceFilePath, toPath: destinationFilePath) }
There is also another method available that accepts a URL parameter instead of a file path. You can check it in Apple documentation.

10. List Files in a Directory

This sample code shows you how to get a list of files that exist in a directory.
func listFiles() { let fileManager = FileManager.default let directoryPath = "/Users/user/Documents" do { let files = try fileManager.contentsOfDirectory(atPath: directoryPath) for file in files { if file.hasSuffix(".txt") { print(file) } } } catch { print(error.localizedDescription) } }
You can check the documentation here.

Wrap Up

Thats it. You can perform file operations in Swift using the File Manager. FileManager class provides you with a common operation method that you can use by providing the String path, or you can use the URL method instead.

Discussion (0)

Related Posts