OC中文件读取类(NSFileHandle)介绍和常用使用方法
生活随笔
收集整理的這篇文章主要介紹了
OC中文件读取类(NSFileHandle)介绍和常用使用方法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
NSFileHandle
1.NSFileManager類主要對于文件的操作(刪除,修改,移動,賦值等等)
//判斷是否有 tagetPath 文件路徑,沒有就創(chuàng)建NSFileManager *fileManage = [NSFileManager defaultManager];BOOL success = [fileManage createFileAtPath:tagetPath contents:nil attributes:nil];if (success) {NSLog(@"create success");}2.NSFileHandle類主要對文件的內(nèi)容進(jìn)行讀取和寫入操作
①NSFileHandle處理文件的步驟
1:創(chuàng)建一個NSFileHandle對象
//創(chuàng)建流NSFileHandle *inFileHandle = [NSFileHandle fileHandleForReadingAtPath:srcPath];NSFileHandle *outFileHandle = [NSFileHandle fileHandleForWritingAtPath:tagetPath];2:對打開的文件進(jìn)行I/O操作
//獲取文件路徑NSString *homePath = NSHomeDirectory();NSString *filePath = [homePath stringByAppendingPathComponent:@"phone/Date.text"];NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];//定位到最后[fileHandle seekToEndOfFile];//定位到某個位置,100字節(jié)之后[fileHandle seekToFileOffset:100];//追加的數(shù)據(jù)NSString *str = @"add world";NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding];//追加寫入數(shù)據(jù)[fileHandle writeData:stringData];3:關(guān)閉文件對象操作
//關(guān)閉流[fileHandle closeFile];常用處理方法,讀
//讀取文件內(nèi)容 void readByFile(){//文件路徑NSString *homePath = NSHomeDirectory();NSString *filePath = [homePath stringByAppendingPathComponent:@"phone/cellPhone.text"];NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];NSInteger length = [fileHandle availableData].length;//跳轉(zhuǎn)到指定位置[fileHandle seekToFileOffset:length/2];NSData *data = [fileHandle readDataToEndOfFile];NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];NSLog(@"%@",str);[fileHandle closeFile];}復(fù)制文件
void copy2Other(){NSString *homePath = NSHomeDirectory();NSString *filePath = [homePath stringByAppendingPathComponent:@"phone/cellPhone.text"];NSString *tagetPath = [homePath stringByAppendingPathComponent:@"phone/cellPhone_bak.text"];//是否有這個文件,沒有則創(chuàng)建NSFileManager *fileManage =[NSFileManager defaultManager];BOOL success = [fileManage createFileAtPath:tagetPath contents:nil attributes:nil];if (success) {NSLog(@"create success");}//通過 NSFileHandle 讀取源文件,寫入另一文件中NSFileHandle *outFileHandle = [NSFileHandle fileHandleForWritingAtPath:tagetPath];NSFileHandle *inFileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];NSData *data = [inFileHandle readDataToEndOfFile];[outFileHandle writeData:data];//關(guān)閉流[inFileHandle closeFile];[outFileHandle closeFile]; }轉(zhuǎn)載于:https://www.cnblogs.com/ShaoYinling/p/4746541.html
總結(jié)
以上是生活随笔為你收集整理的OC中文件读取类(NSFileHandle)介绍和常用使用方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: easybcd 支持 windows 1
- 下一篇: POJ - 3842 An Indus