Bỏ qua để đến nội dung

Đọc và Ghi File

Swift sử dụng FileManager và String/Data để làm việc với files.

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)
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)")
}
let filePath = documentsPath.appendingPathComponent("greeting.txt")
do {
let content = try String(contentsOf: filePath, encoding: .utf8)
print(content)
} catch {
print("Error reading file: \(error)")
}
let data = "Binary content".data(using: .utf8)!
let filePath = documentsPath.appendingPathComponent("data.bin")
do {
try data.write(to: filePath)
} catch {
print("Error: \(error)")
}
do {
let data = try Data(contentsOf: filePath)
if let content = String(data: data, encoding: .utf8) {
print(content)
}
} catch {
print("Error: \(error)")
}
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)
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)
}
}
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")")
}
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)")
}

  • 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