| 方法 | 用途 |
|---|---|
+fileHandleForReadingAtPath: | 唯讀開啟 |
+fileHandleForWritingAtPath: | 唯寫開啟 (截斷現有內容) |
+fileHandleForUpdatingAtPath: | 讀寫開啟 |
-availableData | 回傳可讀資料 (至 EOF) |
-readDataToEndOfFile | 從目前位置讀至檔案結尾 |
-readDataOfLength: | 讀取指定長度 |
-writeData: | 寫入 NSData |
-offsetInFile | 取得目前位移 (unsigned long long) |
-seekToEndOfFile | 移至檔案結尾 |
-seekToFileOffset: | 移至指定位移 |
-truncateFileAtOffset: | 設定檔案長度 (截斷/擴展) |
-synchronizeFile | 強制寫入磁碟 |
-closeFile | 關閉檔案描述符 |
@autoreleasepool {
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/testfile"];
NSFileHandle *fh = [NSFileHandle fileHandleForUpdatingAtPath:path];
[fh seekToEndOfFile];
NSString *str = @"測試附加資料";
[fh writeData:[str dataUsingEncoding:NSUTF8StringEncoding]];
[fh closeFile];
}
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/testfile"];
NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:path];
NSUInteger len = [fh availableData].length;
[fh seekToFileOffset:len / 2]; // 移至中間
NSData *data = [fh readDataToEndOfFile];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);
[fh closeFile];
NSString *srcPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/testfile"];
NSString *dstPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/outfile"];
[[NSFileManager defaultManager] createFileAtPath:dstPath contents:nil attributes:nil];
NSFileHandle *inFH = [NSFileHandle fileHandleForReadingAtPath:srcPath];
NSFileHandle *outFH = [NSFileHandle fileHandleForWritingAtPath:dstPath];
[outFH writeData:[inFH availableData]]; // 一次性讀寫 (小檔案適用)
[inFH closeFile];
[outFH closeFile];
const size_t CHUNK = 1024 * 1024; // 1MB
NSFileHandle *in = [NSFileHandle fileHandleForReadingAtPath:srcPath];
NSFileHandle *out = [NSFileHandle fileHandleForWritingAtPath:dstPath];
while (1) {
NSData *chunk = [in readDataOfLength:CHUNK];
if (chunk.length == 0) break;
[out writeData:chunk];
}
[in closeFile];
[out closeFile];
[str dataUsingEncoding:NSUTF8StringEncoding] → NSData[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] → NSString[data bytes] → const void* 原始指標[data length] → 位元組長度
NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:path];
if (!fh) {
NSLog(@"無法開啟檔案: %@", path);
return;
}
@try {
NSData *data = [fh readDataToEndOfFile];
// 處理 data
}
@catch (NSException *e) {
NSLog(@"讀取異常: %@", e.reason);
}
@finally {
[fh closeFile];
}
使用 NSFileHandleReadCompletionNotification、NSFileHandleWriteCompletionNotification 搭配 readInBackgroundAndNotify/writeData:completionHandler: 實現非阻塞讀寫。