NSFileHandle
NSFileManager類主要對于文件的操作(刪除,修改,移動,賦值等等)
NSFileHandle類主要對文件的內(nèi)容進(jìn)行讀取和寫入操作
NSFileHandle處理文件的步驟
1:創(chuàng)建一個NSFileHandle對象
2:對打開的文件進(jìn)行I/O操作
3:關(guān)閉文件對象操作
常用處理方法
+ (id)fileHandleForReadingAtPath:(NSString *)path; //打開一個文件準(zhǔn)備讀取 + (id)fileHandleForWritingAtPath:(NSString *)path; //打開一個文件準(zhǔn)備寫入 + (id)fileHandleForUpdatingAtPath:(NSString *)path; //打開一個文件可以更新(讀取,寫入) - (NSData *)availableData; //返回可用的數(shù)據(jù) - (NSData *)readDataToEndOfFile; //從當(dāng)前的節(jié)點位置讀取到文件末尾 - (NSData *)readDataOfLength:(NSUInteger)length; //從當(dāng)前的節(jié)點位置開始讀取指定長度的數(shù)據(jù) - (void)writeData:(NSData *)data; //寫入數(shù)據(jù) - (unsigned long long)offsetInFile; //獲取當(dāng)前文件的偏移量 - (unsigned long long)seekToEndOfFile; //跳轉(zhuǎn)到文件結(jié)尾 - (void)seekToFileOffset:(unsigned long long)offset; //跳轉(zhuǎn)到指定文件的指定的偏移量的位置 - (void)truncateFileAtOffset:(unsigned long long)offset; //設(shè)置文件長度 - (void)synchronizeFile; //文件同步 - (void)closeFile; //關(guān)閉文件
實例代碼
1(對文件進(jìn)行加入數(shù)據(jù):):
@autoreleasepool {NSString *homePath=NSHomeDirectory(); NSLog(@"%@",homePath); NSString *filePath=[homePath stringByAppendingFormat:@"/Desktop/testfile"]; NSLog(@"%@",filePath); NSFileHandle *fileHandle=[NSFileHandle fileHandleForUpdatingAtPath:filePath]; [fileHandle seekToEndOfFile]; NSString *str=@"測試加入的數(shù)據(jù)為"; NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding]; [fileHandle writeData:data]; [fileHandle closeFile]; } return 0;
2:對文件中的數(shù)據(jù)進(jìn)行定位:
NSString *homePath=NSHomeDirectory(); NSString *filePath=[homePath stringByAppendingFormat:@"/Desktop/testfile"]; 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);
[特別講一下NSData類的一些方法]
3:復(fù)制文件中的數(shù)據(jù)
//復(fù)制文件 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]; //讀出文件中所有的數(shù)據(jù) //下面開始進(jìn)行寫文件 [outFileHandle writeData:inData]; [inFileHandle closeFile]; [outFileHandle closeFile];