【day0201_NSFileHandle】:文件句柄
1 NSFileHandle 文件对接器、文件句柄
常用API:
- (NSData *)readDataToEndOfFile; 读取数据到最后
- (NSData *)readDataOfLength:(NSUInteger)length; 读取长度
- (void)writeData:(NSData *)data; 写数据
- (unsigned long long)seekToEndOfFile; 将文件指针移至最后,并返回文件长度
- (void)seekToFileOffset:(unsigned long long)offset; 指定文件指针位置
- (void)closeFile; 关闭文件,一般写完/读完数据要关闭文件
+ (id)fileHandleForReadingAtPath:(NSString *)path; 根据路径读取数据
+ (id)fileHandleForWritingAtPath:(NSString *)path; 根据路径写数据
案例代码:
写入:NSString -> 文件
读取:文件 -> NSString
- (void)viewDidLoad { [super viewDidLoad]; NSString *homePath = NSHomeDirectory(); NSLog(@"%@",homePath); NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; NSString *filePath = [documentsPath stringByAppendingPathComponent:@"hello.txt"]; NSString *fileContent = @"你好"; // 写入: // 怎么把fileContent写到hello.txt呢 // 先把fileContent->NSData , 然后写到hello.txt中 // NSString -> NSData NSData *data = [fileContent dataUsingEncoding:NSUTF8StringEncoding]; // NSData -> 文件 完整步骤 // 准备空文件hello.txt NSFileManager *fileManager = [NSFileManager defaultManager]; [fileManager createFileAtPath:filePath contents:nil attributes:nil]; // 创建文件对接器 NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath]; // 写入数据 [fileHandle writeData:data]; // 关闭文件对接器 [fileHandle closeFile]; // 写入文件还有更快捷的方法 // [fileManager createFileAtPath:filePath contents:data attributes:nil]; // 读取 // 文件 -> NSData -> NSString // 创建文件对接器 NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:filePath]; // 读数据 NSData *data1 = [readHandle readDataToEndOfFile]; // 关闭对接器 [readHandle closeFile]; // data -> string NSString *str = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding]; NSLog(@"%@",str); // string根据路径可以直接获取数据 NSString *str2 = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; // 读取文件以UTF8显示 // 识别编码 NSStringEncoding encode; NSString *str3 = [NSString stringWithContentsOfFile:filePath usedEncoding:&encode error:nil]; // 该方法做了两件事,首先根据路径读取数据,然后把该数据的编码赋值给encode NSLog(@"%d",encode); // 4 表示UTF8编码 }
【day0202_copyFileContent】:copy文件
练习:
先用NSString -> 文件
往Documents下写一个文件source.txt
文件的内容随便,有中文
需要写代码拷贝文件 -> copy .txt
源文件 -> NSData-> 新文件
FileHandle NSData
- (void)viewDidLoad { [super viewDidLoad]; NSLog(@"%@",NSHomeDirectory()); NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES)[0]; NSString *filePath = [documentsPath stringByAppendingPathComponent:@"sourcefile.txt"]; NSData *data = [@"中文!" dataUsingEncoding:NSUTF8StringEncoding]; [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]; [[NSFileManager defaultManager] createFileAtPath:filePath contents:data attributes:nil]; // 文件 -> data NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:filePath]; NSData *dataFromFile = [readHandle readDataToEndOfFile]; // data -> 新文件copy.txt NSString *copyPath = [documentsPath stringByAppendingPathComponent:@"copy.txt"]; [[NSFileManager defaultManager] createFileAtPath:copyPath contents:dataFromFile attributes:nil]; // copy图片 NSData *picData = [NSData dataWithContentsOfFile:@"/Users/.../01.jpg"]; NSString *picPath = [documentsPath stringByAppendingPathComponent:@"01.jpg"]; [[NSFileManager defaultManager] createFileAtPath:picPath contents:picData attributes:nil]; }
【day0203_merge合并文件】
合并一些文件的内容到新文件中
- (void)viewDidLoad { [super viewDidLoad]; NSLog(@"%@",NSHomeDirectory()); // 获取documents路径 NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; // 源文件名数组 NSArray *sourceNames = @[@"a.txt", @"b.txt", @"c.txt",]; // 合并文件名 NSString *outputName = @"combine.txt"; // 合并文件路径 NSString *outputFilePath = [documents stringByAppendingPathComponent:outputName]; // 创建合并文件 [[NSFileManager defaultManager] createFileAtPath:outputFilePath contents:nil attributes:nil]; // 创建filehandle NSFileHandle *writeHandle = [NSFileHandle fileHandleForWritingAtPath:outputFilePath]; // 循环写入数据 for (NSString *sourceName in sourceNames) { NSString *sourceFilePath = [documents stringByAppendingPathComponent:sourceName]; // 源文件路径 NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:sourceFilePath]; // 创建读取handle NSData *readData = [readHandle readDataToEndOfFile]; // 读出数据 [writeHandle writeData:readData]; // 写到新文件中 [readHandle closeFile]; // 关闭读取文件 } // 关闭文件 [writeHandle closeFile]; }
【day0204_FilePointer文件指针】
文件指针的使用
按指定字节拷贝文件
- (void)viewDidLoad { [super viewDidLoad]; NSLog(@"%@",NSHomeDirectory()); NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; NSString *sourcePath = [documentsPath stringByAppendingPathComponent:@"source.txt"]; // 按每次1000字节的中专 拷贝一张图片 NSString *picPath = @"/Users/tarena/yz/第三阶段(UI核心_Model赵哲)/day02/1-4.jpg"; // 拷贝 // 创建读取handle NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:picPath]; unsigned long long picSize = [readHandle seekToEndOfFile]; // 图片大小 unsigned long long offset = 0; NSString *path = [documentsPath stringByAppendingPathComponent:@"0.jpg"]; // document下图片路径 [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil]; // 创建空jpg文件 NSFileHandle *writeHandle = [NSFileHandle fileHandleForWritingAtPath:path]; // 创建写handle [readHandle seekToFileOffset:0]; // 设置文件指针 // 循环读取文件写入到document下空的jpg文件 NSData *data = nil; while (offset + 1000 <= picSize) { // 一次读1000 data = [readHandle readDataOfLength:1000]; [writeHandle writeData:data]; offset += 1000; NSLog(@"%llu",offset); } // 不足1000的读到最后 data = [readHandle readDataToEndOfFile]; [writeHandle writeData:data]; [readHandle closeFile]; [writeHandle closeFile]; // 文件指针的使用 NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:sourcePath]; unsigned long long fileSize = [readHandle seekToEndOfFile]; // 该方法会把文件指针移至最后并返回文件大小 NSLog(@"%llu",fileSize); [readHandle seekToFileOffset:0]; // 设置指针位置 NSData *data = [readHandle readDataOfLength:3]; // 读取长度 以字节为单位 一个汉子占3个字节 NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",str); [readHandle closeFile]; }
【day0205_文件查看器】
MXDocumentsViewController.m
- (void)viewDidLoad { [super viewDidLoad]; if (!self.path) { self.path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; } NSArray *fileNameArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.path error:nil]; self.files = [NSMutableArray array]; for (NSString *fileName in fileNameArray) { NSString *filePath = [self.path stringByAppendingPathComponent:fileName]; [self.files addObject:filePath]; } NSLog(@"%@",self.files); // Uncomment the following line to preserve selection between presentations. // self.clearsSelectionOnViewWillAppear = NO; // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - Table view data source - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.files.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; // Configure the cell... NSString *filePath = self.files[indexPath.row]; if ([[filePath pathExtension] isEqualToString:@"jpg"]) { cell.textLabel.text = [filePath lastPathComponent]; cell.imageView.image = [UIImage imageWithContentsOfFile:filePath]; }else if([[filePath pathExtension] isEqualToString:@"txt"]){ cell.textLabel.text = [filePath lastPathComponent]; }else{ //目录 cell.textLabel.text = [filePath lastPathComponent]; [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]; } return cell; } -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ NSString *filePath = self.files[indexPath.row]; if ([[filePath pathExtension] isEqualToString:@"jpg"]) { [self performSegueWithIdentifier:@"pictureVC" sender:filePath]; }else if([[filePath pathExtension] isEqualToString:@"txt"]){ [self performSegueWithIdentifier:@"txtVC" sender:filePath]; }else{ //目录 MXDocumentsViewController *docvc = [self.storyboard instantiateViewControllerWithIdentifier:@"fileListTV"]; docvc.path = filePath; [self.navigationController pushViewController:docvc animated:YES]; } } #pragma mark - Navigation // In a story board-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"pictureVC"]) { MXPictureViewController *picvc = segue.destinationViewController; picvc.path = sender; }else if ([segue.identifier isEqualToString:@"txtVC"]){ MXTxtViewController *txtvc = segue.destinationViewController; txtvc.path = sender; } }
02-IOSCore - NSFileHandle、合并文件、文件指针、文件查看器,布布扣,bubuko.com
02-IOSCore - NSFileHandle、合并文件、文件指针、文件查看器
原文:http://www.cnblogs.com/yangmx/p/3583084.html