- 转自http://www.it165.net/pro/html/201402/9100.html
-
NSFileHandle
NSFileManager类主要对于文件的操作(删除,修改,移动,赋值等等)
NSFileHandle类主要对文件的内容进行读取和写入操作
NSFileHandle处理文件的步骤
1:创建一个NSFileHandle对象
2:对打开的文件进行I/O操作
3:关闭文件对象操作
常用处理方法
01.+ (id)fileHandleForReadingAtPath:(NSString *)path;//打开一个文件准备读取02.+ (id)fileHandleForWritingAtPath:(NSString *)path;//打开一个文件准备写入03.+ (id)fileHandleForUpdatingAtPath:(NSString *)path;//打开一个文件可以更新(读取,写入)04.- (NSData *)availableData;//返回可用的数据05.- (NSData *)readDataToEndOfFile;//从当前的节点位置读取到文件末尾06.- (NSData *)readDataOfLength:(NSUInteger)length;//从当前的节点位置开始读取指定长度的数据07.- (void)writeData:(NSData *)data;//写入数据08.- (unsignedlonglong)offsetInFile;//获取当前文件的偏移量09.- (unsignedlonglong)seekToEndOfFile;//跳转到文件结尾10.- (void)seekToFileOffset:(unsignedlonglong)offset;//跳转到指定文件的指定的偏移量的位置11.- (void)truncateFileAtOffset:(unsignedlonglong)offset;//设置文件长度12.- (void)synchronizeFile;//文件同步13.- (void)closeFile;//关闭文件
实例代码
1(对文件进行加入数据:):
@autoreleasepool {01.NSString *homePath=NSHomeDirectory();02.NSLog(@"%@",homePath);03.04.NSString *filePath=[homePath stringByAppendingFormat:@"/Desktop/testfile"];05.NSLog(@"%@",filePath);06.NSFileHandle *fileHandle=[NSFileHandle fileHandleForUpdatingAtPath:filePath];07.08.[fileHandle seekToEndOfFile];09.NSString *str=@"测试加入的数据为";10.NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];11.[fileHandle writeData:data];12.[fileHandle closeFile];13.}14.return0;![\]()
2:对文件中的数据进行定位:
1.NSString *homePath=NSHomeDirectory();2.NSString *filePath=[homePath stringByAppendingFormat:@"/Desktop/testfile"];3.NSFileHandle *fileHandle=[NSFileHandle fileHandleForReadingAtPath:filePath];4.NSUInteger length= [fileHandle availableData].length;5.[fileHandle seekToFileOffset:length/2];6.NSData *data=[fileHandle readDataToEndOfFile];7.NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];8.NSLog(@"%@",str);1.1.![\]()
1.[特别讲一下NSData类的一些方法]1.![\]()
1.3:复制文件中的数据1.1.//复制文件 NSString *homePath=NSHomeDirectory(); NSString *filePath=[homePath stringByAppendingFormat:@"/Desktop/testfile"]; //NSFileHandle *fileHandle=[NSFileHandle fileHandleForReadingAtPath:filePath]; NSString *targetPath=[homePath stringByAppendingFormat:@"/Desktop/outfile"]; NSFileManager *fileManager=[NSFileManager defaultManager]; BOOL result=[fileManager createFileAtPath:targetPath contents:nil attributes:nil]; if(result){ NSLog(@"create success!"); } NSFileHandle *inFileHandle=[NSFileHandle fileHandleForReadingAtPath:filePath]; NSFileHandle *outFileHandle=[NSFileHandle fileHandleForWritingAtPath:targetPath]; NSData *inData=[inFileHandle availableData]; //读出文件中所有的数据 //下面开始进行写文件 [outFileHandle writeData:inData]; [inFileHandle closeFile]; [outFileHandle closeFile];



浙公网安备 33010602011771号