萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 檔案讀寫核心類 NSFileHandle 與 NSFileManager 完整指南

iOS 檔案操作兩大核心類別職責劃分

  • NSFileManager:檔案層級操作——建立、刪除、移動、複製、屬性讀取、目錄列舉。
  • NSFileHandle:檔案內容流式讀寫——開啟、讀取、寫入、定位、關閉,支援斷點續傳。

NSFileHandle 基本操作流程

  1. 建立 Handle:fileHandleForReadingAtPath:、fileHandleForWritingAtPath:、fileHandleForUpdatingAtPath:
  2. I/O 操作:readDataToEndOfFile、readDataOfLength:、writeData:、seekToFileOffset:、seekToEndOfFile
  3. 關閉:closeFile

實戰程式碼範例

1. 讀取檔案後半段內容

let home = NSHomeDirectory()
let path = (home as NSString).appendingPathComponent("Desktop/hello.rtf")
guard let handle = FileHandle(forReadingAtPath: path) else { return }
let length = handle.availableData.count
handle.seek(toFileOffset: UInt64(length/2))
let data = handle.readDataToEndOfFile()
let str = String(data: data, encoding: .utf8)
print(str ?? "")

2. 追加寫入指定位移

guard let handle = FileHandle(forUpdatingAtPath: path) else { return }
handle.seek(toFileOffset: 10)
let data = "data".data(using: .utf8)!
handle.write(data)
handle.closeFile()

3. 複製檔案(串流式,適合大檔)

let src = (home as NSString).appendingPathComponent("Desktop/hello.rtf")
let dst = (home as NSString).appendingPathComponent("Desktop/copy.rtf")
FileManager.default.createFile(atPath: dst, contents: nil, attributes: nil)
guard let readH = FileHandle(forReadingAtPath: src),
      let writeH = FileHandle(forWritingAtPath: dst) else { return }
let data = readH.readDataToEndOfFile()
writeH.write(data)
readH.closeFile()
writeH.closeFile()

關鍵提示

  • 沙盒路徑請用 NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! 取得。
  • 大檔案請分塊讀寫,避免記憶體壓力。
  • 異步操作建議放在背景佇列,完成後回主佇列更新 UI。

掌握這兩個類別,即可應對 iOS 絕大多數檔案讀寫需求。

copyright © 萬盛學電腦網 all rights reserved