第一、NSFileHandle
NSFileManager類主要對檔案的操作(刪除、修改、移動、複製等)
NSFileHandle類主要對檔案的內容進行讀取和寫入
第二、NSFileHandle類處理檔案的步驟
建立一個NSFileHandle對象
對開啟的檔案進行I/0操作
關閉檔案
可以使用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];
// insert code here...
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];