第一、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];