NSFileHandle主要对已经存在的文件进行修改操作
NSFileHandle常用方法
+(NSFileHandle *)fileHandleForReadingAtPath:path 打开一个文件用于读入
+(NSFileHandle *)fileHandleForWritingAtPath:path 打开一个文件用于写入
+(NSFileHandle *)fileHandleForUpdatingAtPath:path 打开一个文件用于读写
-(NSData *)readDataToEndOfFile 读取其余数据直到文件末尾
-(NSData *)readDataOfLength:(NSUInteger)bytes 从文件中读取制定字节的内容
-(void)writeData:data 将data写入文件
偏移量:决定光标位置
-(unsigned long long)offsetInFile 获取当前偏移量
-(void)seekToFileOffset :offset 设置偏移量
-(unsigned long long)seekToEndOfFile 将偏移量定位到文件的末尾
-(void)truncateFileAtOffset:offset 将文件的长度设置为offset字节
-(void)closeFile 关闭文件
读写文件代码
//读写文件 NSFileManager *fm =[NSFileManager defaultManager]; NSString *outFilePath = @"outFile.txt"; NSString *contentStr = @"Hello World!"; NSString *inFilePath = @"inFile.txt"; [fm createFileAtPath:outFilePath contents:[contentStr dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]; [fm createFileAtPath:inFilePath contents:nil attributes:nil]; NSFileHandle *outHandle = [NSFileHandle fileHandleForReadingAtPath:outFilePath]; NSFileHandle *inHandle = [NSFileHandle fileHandleForWritingAtPath:inFilePath]; if(outHandle == nil || inHandle == nil) { NSLog(@"文件并不存在!"); } else { NSData *data = [outHandle readDataToEndOfFile]; [inHandle truncateFileAtOffset:0]; //清空文件内容 [inHandle writeData:data]; NSLog(@"写入完成!"); [outHandle closeFile]; [inHandle closeFile]; }
修改文件代码
//修改文件 NSFileHandle *updateHandle = [NSFileHandle fileHandleForUpdatingAtPath:inFilePath]; NSString *str = @"追加内容"; [updateHandle seekToEndOfFile]; [updateHandle writeData:[str dataUsingEncoding:NSUTF8StringEncoding]]; [updateHandle closeFile];