要處理大檔案、或需要「跳到某個位置寫入幾個 byte」這種細粒度操作時,NSFileHandle 比整包讀寫的 NSData 更合適。以下把它的方法依用途分類。
+ (id)fileHandleForReadingAtPath:(NSString *)path; // 只讀 + (id)fileHandleForWritingAtPath:(NSString *)path; // 只寫(會從頭覆寫) + (id)fileHandleForUpdatingAtPath:(NSString *)path; // 讀寫皆可
三者都是「打開既有檔案」,不會幫你建立新檔;檔案不存在時會回傳 nil,使用前記得判斷。
- (NSData *)availableData; // 讀取目前可用的資料 - (NSData *)readDataToEndOfFile; // 從目前位置一路讀到檔尾 - (NSData *)readDataOfLength:(NSUInteger)length; // 讀取指定長度
- (void)writeData:(NSData *)data; // 寫入 - (unsigned long long)offsetInFile; // 目前讀寫位置 - (unsigned long long)seekToEndOfFile; // 跳到檔尾 - (void)seekToFileOffset:(unsigned long long)offset; // 跳到指定偏移 - (void)truncateFileAtOffset:(unsigned long long)offset; // 把檔案截成指定長度 - (void)synchronizeFile; // 立刻落盤 - (void)closeFile; // 關檔
典型的「附加一行」流程就是:開寫入模式 → seekToEndOfFile → writeData → closeFile。而 truncateFileAtOffset: 常用於把檔案砍掉尾巴,例如log 輪替。
不需要 NSFileHandle,用 NSFileManager 問檔案屬性即可:
NSFileManager *defaultManager = [NSFileManager defaultManager]; NSDictionary *dic = [defaultManager attributesOfItemAtPath:filePath error:nil]; NSNumber *fileNum = [dic objectForKey:NSFileSize]; NSLog(@"fileNum : %f", [fileNum floatValue]);
要注意 NSFileHandle 的 seek 與 write 都是有狀態的,同一個 handle 若不留意目前 offset,很容易寫到意料之外的位置;用完關檔、需要重定位就先 seek,是最省事的習慣。