iOS 的文件操作主要圍繞兩個類展開,分工非常清晰:
NSFileManager —— 負責文件本身的組織:刪除、複製、移動、重命名、查詢屬性等。
NSFileHandle —— 負責文件內容的讀寫:定位偏移、讀取片段、追加數據。
正因為它可以自由控制讀寫指針的位置,NSFileHandle 天然適合實現斷點續傳 —— 只需記錄已下載的字節數,下次從該偏移量繼續寫入即可。
下面的例子實現「從文件中間開始讀到結尾」,這正是斷點續傳的核心邏輯:
NSString *homePath = NSHomeDirectory(); NSString *filePath = [homePath stringByAppendingPathComponent:@"Desktop/hello.rtf"]; NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath]; // 先取得總長度 NSUInteger length = [fileHandle availableData].length; // 把讀寫指針移動到一半位置 [fileHandle seekToFileOffset:length / 2]; // 從當前位置讀到文件末尾 NSData *data = [fileHandle readDataToEndOfFile]; NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", str);
這裡有個值得優化的地方:availableData 會把整個文件讀進內存,用來取長度代價太高。更合適的選擇是 [fileHandle seekToEndOfFile](返回值即為文件長度),或直接調用 NSFileManager 的 attributesOfItemAtPath:error: 取 NSFileSize。
NSString *homePath = NSHomeDirectory(); NSString *filePath = [homePath stringByAppendingPathComponent:@"Desktop/hello.rtf"]; // 以「可更新」模式打開,文件不存在時返回 nil NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath]; // 若要追加到末尾,使用 seekToEndOfFile // [fileHandle seekToEndOfFile]; // 這裡演示從第 10 個字節開始覆寫 [fileHandle seekToFileOffset:10]; NSString *str = @"data"; NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; [fileHandle writeData:data]; [fileHandle closeFile];
fileHandleForUpdatingAtPath: 同時支持讀與寫。要注意 seek 到指定偏移後 writeData 是覆蓋而非插入,若原文件該位置已有內容會被直接替換掉。
純文件級的複製其實用 NSFileManager 一行就能搞定,下面的寫法則展示了如何用 FileHandle 做「分塊搬運」,適合處理大文件:
NSString *homePath = NSHomeDirectory(); NSString *filePath = [homePath stringByAppendingPathComponent:@"Desktop/hello.rtf"]; NSString *objPath = [homePath stringByAppendingPathComponent:@"Desktop/copy.rtf"]; NSFileManager *fileManager = [NSFileManager defaultManager]; BOOL success = [fileManager createFileAtPath:objPath contents:nil attributes:nil]; NSFileHandle *writeFile = [NSFileHandle fileHandleForReadingAtPath:filePath]; NSFileHandle *objFile = [fileHandle fileHandleForWritingAtPath:objPath]; NSData *data = [writeFile readDataToEndOfFile]; [objFile writeData:data]; [writeFile closeFile]; [objFile closeFile];
更簡潔的等價寫法:
NSError *error = nil; [[NSFileManager defaultManager] copyItemAtPath:filePath toPath:objPath error:&error];
路徑獲取。示例中的 NSHomeDirectory() 在 iOS 應用中指向 App 沙盒根目錄。實際開發更常用 NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) 取得 Documents 目錄,或使用 NSFileManager 的 URLForDirectory:inDomain:appropriateForURL:create:error:。
讀寫大文件時分塊。readDataToEndOfFile 一次性加載全部內容,對大文件會造成內存峰值。可以改用 readDataOfLength: 配合循環與偏移量。
判斷返回值。fileHandleForWritingAtPath: 在文件不存在時返回 nil,使用前應做判斷,否則後續消息發送雖不崩潰但會靜默失敗。
推薦使用 URL 系 API。路徑字符串 API 在後續系統版本中已被標記為廢棄,新代碼應使用 URLsForDirectory:inDomains: 與 NSFileManager 的 URL 參數版本。