您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 學習筆記:NSFileHandle 讀寫檔案的常用方法

編輯:iOS 開發綜合

兩個類的分工

首先要區分兩個類:NSFileManager 主要負責對檔案本身的操作(刪除、修改、移動、複製等);NSFileHandle 則主要負責對檔案內容進行讀取與寫入。

NSFileHandle 的處理步驟

  1. 建立一個 NSFileHandle 物件。
  2. 對打開的檔案進行 IO 操作。
  3. 關閉檔案。

值得一提的是,借助 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);

實現追加

NSString *homePath = NSHomeDirectory();
NSString *filePath = [homePath stringByAppendingPathComponent:@"Desktop/hello.rtf"];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
// [fileHandle seekToEndOfFile];
[fileHandle seekToFileOffset:10];
NSString *str = @"data";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[fileHandle writeData:data];
[fileHandle closeFile];
NSLog(@"Hello, World!");

實現複製

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 = [NSFileHandle fileHandleForWritingAtPath:objPath];
[objFile readDataToEndOfFile];
NSData *data = [writeFile readDataToEndOfFile];
[objFile writeData:data];
[writeFile closeFile];
[objFile closeFile];
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved