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