Giới thiệu
Lập trình viên iOS cần biết thao tác cơ bản với file hệ thống: tạo file, ghi dữ liệu, đọc dữ liệu. Bài viết dùng FileManager và String API của Swift.
Các bước thực hiện
Bước 1: Tạo dự án
Xcode → New Project → Single View Application → Tên "ReadingWritingFile".
Bước 2: Tạo hàm ghi & đọc file
func createReadAndWriteFile() {
// 1. Xác định đường dẫn Document Directory
let fileName = "sample"
let documentDirectoryUrl = try! FileManager.default.url(
for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
// 2. Tạo file URL (sample.txt)
let fileUrl = documentDirectoryUrl
.appendingPathComponent(fileName)
.appendingPathExtension("txt")
print("Đường dẫn file: \(fileUrl.path)")
// 3. Dữ liệu cần ghi
let stringData = "Hello Tutorials Point."
// 4. Ghi file (utf8, atomic write)
do {
try stringData.write(to: fileUrl, atomically: true, encoding: .utf8)
print("Ghi file thành công")
} catch {
print("Lỗi ghi file: \(error)")
}
// 5. Đọc file
var readContent = ""
do {
readContent = try String(contentsOf: fileUrl, encoding: .utf8)
print("Nội dung đọc được: \(readContent)")
} catch {
print("Lỗi đọc file: \(error)")
}
}
Bước 3: Gọi hàm trong viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
createReadAndWriteFile()
}
Bước 4: Chạy và kiểm tra
Xcode Console sẽ in đường dẫn file và nội dung. Để xem file thực tế:
- Xcode → Devices and Simulators → chọn simulator → Download Container.
- Chuột phải container → Show Package Contents → AppData/Documents/sample.txt.

Mã nguồn hoàn chỉnh
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
createReadAndWriteFile()
}
func createReadAndWriteFile() {
let fileName = "sample"
let documentDirectoryUrl = try! FileManager.default.url(
for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true
)
let fileUrl = documentDirectoryUrl
.appendingPathComponent(fileName)
.appendingPathExtension("txt")
print("File path: \(fileUrl.path)")
let stringData = "Hello Tutorials Point."
do {
try stringData.write(to: fileUrl, atomically: true, encoding: .utf8)
} catch {
print("Write error: \(error)")
}
var readFile = ""
do {
readFile = try String(contentsOf: fileUrl, encoding: .utf8)
} catch {
print("Read error: \(error)")
}
print("Read content: \(readFile)")
}
}
Mở rộng: Ghi/đọc đối tượng (Codable)
struct User: Codable {
let name: String
let age: Int
}
// Ghi
let user = User(name: "An", age: 25)
let encoder = JSONEncoder()
if let data = try? encoder.encode(user) {
try? data.write(to: fileUrl)
}
// Đọc
if let data = try? Data(contentsOf: fileUrl),
let user = try? JSONDecoder().decode(User.self, from: data) {
print("User: \(user.name), \(user.age)")
}
Lưu ý
- Luôn dùng
try?hoặcdo-catchđể xử lý lỗi I/O. atomically: trueghi vào file tạm rồi rename → an toàn nếu crash giữa chừng.- Document Directory được backup bởi iCloud (trừ khi exclude).
- Dùng
.cachesDirectorycho file tạm, không cần backup.