Skip to Content
Swift📘 Ngôn ngữ SwiftĐọc và Ghi File

Đọc và Ghi File trong Swift

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

import Foundation // Documents directory let documentsPath = FileManager.default.urls( for: .documentDirectory, in: .userDomainMask )[0] // Tạo file path let filePath = documentsPath.appendingPathComponent("data.txt") print(filePath.path)

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

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)

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

do { let data = try Data(contentsOf: filePath) if let content = String(data: data, encoding: .utf8) { print(content) } } catch { print("Error: \(error)") }

7. FileManager Operations

let fileManager = FileManager.default // Kiểm tra tồn tại if fileManager.fileExists(atPath: filePath.path) { print("File exists") } // Xóa file try? fileManager.removeItem(at: filePath) // Copy file try? fileManager.copyItem(at: source, to: destination) // Move file try? fileManager.moveItem(at: source, to: destination)

8. Làm việc với Directories

let fileManager = FileManager.default let newDir = documentsPath.appendingPathComponent("MyFolder") // Tạo directory try? fileManager.createDirectory( at: newDir, withIntermediateDirectories: true, attributes: nil ) // Liệt kê files if let contents = try? fileManager.contentsOfDirectory(atPath: newDir.path) { for item in contents { print(item) } }

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

struct User: Codable { let name: String let age: Int } // Ghi JSON let 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 JSON do { 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

  • FileManager cho file operations
  • String.write(to:) ghi text
  • String(contentsOf:) đọc text
  • Data.write(to:) ghi binary
  • Data(contentsOf:) đọc binary
  • try-catch cho error handling
  • Codable cho JSON persistence
Last updated on