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];
}