第一、NSFileHandle
NSFileManager類主要對文件的操作(刪除、修改、移動、復(fù)制等)
NSFileHandle類主要對文件的內(nèi)容進(jìn)行讀取和寫入
第二、NSFileHandle類處理文件的步驟
創(chuàng)建一個NSFileHandle對象
對打開的文件進(jìn)行I/0操作
關(guān)閉文件
可以使用NSFileHandle進(jìn)行斷點(diǎn)續(xù)傳
第三、實(shí)現(xiàn)查找功能的代碼:
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);
第四、實(shí)現(xiàn)追加文件代碼:
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!");
第五、實(shí)現(xiàn)復(fù)制文件的代碼:
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];
更多信息請查看IT技術(shù)專欄