Đọc và Ghi File
1. Giới thiệu
Phần tiêu đề “1. Giới thiệu”Swift sử dụng FileManager và String/Data để làm việc với files.
2. Lấy đường dẫn
Phần tiêu đề “2. Lấy đường dẫn”import Foundation
// Documents directorylet documentsPath = FileManager.default.urls( for: .documentDirectory, in: .userDomainMask)[0]
// Tạo file pathlet filePath = documentsPath.appendingPathComponent("data.txt")print(filePath.path)3. Ghi file text
Phần tiêu đề “3. Ghi file text”let text = "Hello, Swift!"let filePath = documentsPath.appendingPathComponent("greeting.txt")
do { try text.write(to: filePath, atomically: true, encoding: .utf8) print("File written successfully")} catch { print("Error writing file: \(error)")}4. Đọc file text
Phần tiêu đề “4. Đọc file text”let filePath = documentsPath.appendingPathComponent("greeting.txt")
do { let content = try String(contentsOf: filePath, encoding: .utf8) print(content)} catch { print("Error reading file: \(error)")}5. Ghi Data (Binary)
Phần tiêu đề “5. Ghi Data (Binary)”let data = "Binary content".data(using: .utf8)!let filePath = documentsPath.appendingPathComponent("data.bin")
do { try data.write(to: filePath)} catch { print("Error: \(error)")}6. Đọc Data
Phần tiêu đề “6. Đọc Data”do { let data = try Data(contentsOf: filePath) if let content = String(data: data, encoding: .utf8) { print(content) }} catch { print("Error: \(error)")}7. FileManager Operations
Phần tiêu đề “7. FileManager Operations”let fileManager = FileManager.default
// Kiểm tra tồn tạiif fileManager.fileExists(atPath: filePath.path) { print("File exists")}
// Xóa filetry? fileManager.removeItem(at: filePath)
// Copy filetry? fileManager.copyItem(at: source, to: destination)
// Move filetry? fileManager.moveItem(at: source, to: destination)8. Làm việc với Directories
Phần tiêu đề “8. Làm việc với Directories”let fileManager = FileManager.defaultlet newDir = documentsPath.appendingPathComponent("MyFolder")
// Tạo directorytry? fileManager.createDirectory( at: newDir, withIntermediateDirectories: true, attributes: nil)
// Liệt kê filesif let contents = try? fileManager.contentsOfDirectory(atPath: newDir.path) { for item in contents { print(item) }}9. File Attributes
Phần tiêu đề “9. File Attributes”let filePath = documentsPath.appendingPathComponent("data.txt")
if let attributes = try? fileManager.attributesOfItem(atPath: filePath.path) { let size = attributes[.size] as? Int64 ?? 0 let modDate = attributes[.modificationDate] as? Date
print("Size: \(size) bytes") print("Modified: \(modDate?.description ?? "Unknown")")}10. Codable với JSON File
Phần tiêu đề “10. Codable với JSON File”struct User: Codable { let name: String let age: Int}
// Ghi JSONlet user = User(name: "Alice", age: 25)let filePath = documentsPath.appendingPathComponent("user.json")
do { let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let data = try encoder.encode(user) try data.write(to: filePath)} catch { print("Error: \(error)")}
// Đọc JSONdo { let data = try Data(contentsOf: filePath) let user = try JSONDecoder().decode(User.self, from: data) print(user)} catch { print("Error: \(error)")}📝 Tóm tắt
Phần tiêu đề “📝 Tóm tắt”- FileManager cho file operations
String.write(to:)ghi textString(contentsOf:)đọc textData.write(to:)ghi binaryData(contentsOf:)đọc binary- try-catch cho error handling
- Codable cho JSON persistence