第一、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(@");
第四、实现追加文件代码:
NSString *homePath=NSHomeDirectory();
NSString *filePath=[homePath stringByAppendingPathComponent:@"Desktop/hello.rtf"];
NSFileHandle *fileHandle=[NSFileHandle fileHandleForUpdatingAtPath:filePath];
//[fileHandle seekToEndOfFile];
[fileHandle seekToFileOffset:10];
NSString ";
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];
更多信息请查看IT技术专栏