【day0201_NSFileHandle】:文件句柄
1 NSFileHandle 文件对接器、文件句柄
常用API:
- (NSData *)readDataToEndOfFile;读取数据到最后
- (NSData *)readDataOfLength:(NSUInteger)length; 读取长度
- (void)writeData:(NSData *)data; 写数据
- (unsignedlonglong)seekToEndOfFile; 将文件指针移至最后,并返回文件长度
- (void)seekToFileOffset:(unsignedlonglong)offset; 指定文件指针位置
- (void)closeFile; 关闭文件,一般写完/读完数据要关闭文件
+ (id)fileHandleForReadingAtPath:(NSString *)path; 根据路径读取数据
+ (id)fileHandleForWritingAtPath:(NSString *)path; 根据路径写数据
案例代码:
/*
写入:NSString -> 文件
读取:文件 -> NSString
*/
- (void)viewDidLoad
{
[superviewDidLoad];
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 = [NSFileManagerdefaultManager];
[fileManager createFileAtPath:filePath contents:nilattributes:nil];
// 创建文件对接器
NSFileHandle *fileHandle = [NSFileHandlefileHandleForWritingAtPath:filePath];
// 写入数据
[fileHandle writeData:data];
// 关闭文件对接器
[fileHandle closeFile];
// 写入文件还有更快捷的方法
// [fileManager createFileAtPath:filePath contents:data attributes:nil];
// 读取
// 文件 -> NSData -> NSString
// 创建文件对接器
NSFileHandle *readHandle = [NSFileHandlefileHandleForReadingAtPath:filePath];
// 读数据
NSData *data1 = [readHandle readDataToEndOfFile];
// 关闭对接器
[readHandle closeFile];
// data -> string
NSString *str = [[NSStringalloc] initWithData:data1 encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
// string根据路径可以直接获取数据
NSString *str2 = [NSStringstringWithContentsOfFile:filePath encoding:NSUTF8StringEncodingerror:nil]; // 读取文件以UTF8显示
// 识别编码
NSStringEncoding encode;
NSString *str3 = [NSStringstringWithContentsOfFile: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
{
[superviewDidLoad];
NSLog(@"%@",NSHomeDirectory());
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES)[0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"sourcefile.txt"];
NSData *data = [@"中文!"dataUsingEncoding:NSUTF8StringEncoding];
[[NSFileManagerdefaultManager] createFileAtPath:filePath contents:nilattributes:nil];
[[NSFileManagerdefaultManager] createFileAtPath:filePath contents:data attributes:nil];
// 文件 -> data
NSFileHandle *readHandle = [NSFileHandlefileHandleForReadingAtPath:filePath];
NSData *dataFromFile = [readHandle readDataToEndOfFile];
// data -> 新文件copy.txt
NSString *copyPath = [documentsPath stringByAppendingPathComponent:@"copy.txt"];
[[NSFileManagerdefaultManager] createFileAtPath:copyPath contents:dataFromFile attributes:nil];
// copy图片
NSData *picData = [NSDatadataWithContentsOfFile:@"/Users/.../01.jpg"];
NSString *picPath = [documentsPath stringByAppendingPathComponent:@"01.jpg"];
[[NSFileManagerdefaultManager] createFileAtPath:picPath contents:picData attributes:nil];
}
【day0203_merge合并文件】
合并一些文件的内容到新文件中
- (void)viewDidLoad
{
[superviewDidLoad];
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];
// 创建合并文件
[[NSFileManagerdefaultManager] createFileAtPath:outputFilePath contents:nilattributes:nil];
// 创建filehandle
NSFileHandle *writeHandle = [NSFileHandlefileHandleForWritingAtPath:outputFilePath];
// 循环写入数据
for (NSString *sourceName in sourceNames) {
NSString *sourceFilePath = [documents stringByAppendingPathComponent:sourceName]; // 源文件路径
NSFileHandle *readHandle = [NSFileHandlefileHandleForReadingAtPath:sourceFilePath]; // 创建读取handle
NSData *readData = [readHandle readDataToEndOfFile]; // 读出数据
[writeHandle writeData:readData]; // 写到新文件中
[readHandle closeFile]; // 关闭读取文件
}
// 关闭文件
[writeHandle closeFile];
}
【day0204_FilePointer文件指针】
文件指针的使用
按指定字节拷贝文件
- (void)viewDidLoad
{
[superviewDidLoad];
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 = [NSFileHandlefileHandleForReadingAtPath:picPath];
unsignedlonglong picSize = [readHandle seekToEndOfFile]; // 图片大小
unsignedlonglong offset = 0;
NSString *path = [documentsPath stringByAppendingPathComponent:@"0.jpg"]; // document下图片路径
[[NSFileManagerdefaultManager] createFileAtPath:path contents:nilattributes:nil]; // 创建空jpg文件
NSFileHandle *writeHandle = [NSFileHandlefileHandleForWritingAtPath: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];
unsignedlonglong fileSize = [readHandle seekToEndOfFile]; // 该方法会把文件指针移至最后并返回文件大小
NSLog(@"%llu",fileSize);
[readHandle seekToFileOffset:0]; // 设置指针位置
NSData *data = [readHandle readDataOfLength:3]; // 读取长度以字节为单位一个汉子占3个字节
NSString *str = [[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
[readHandle closeFile];
}
【day0205_文件查看器】
MXDocumentsViewController.m
- (void)viewDidLoad
{
[superviewDidLoad];
if (!self.path) {
self.path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
}
NSArray *fileNameArray = [[NSFileManagerdefaultManager] contentsOfDirectoryAtPath:self.patherror:nil];
self.files = [NSMutableArrayarray];
for (NSString *fileName in fileNameArray) {
NSString *filePath = [self.pathstringByAppendingPathComponent:fileName];
[self.filesaddObject: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
{
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
returnself.files.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
staticNSString *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 = [UIImageimageWithContentsOfFile:filePath];
}elseif([[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"]) {
[selfperformSegueWithIdentifier:@"pictureVC"sender:filePath];
}elseif([[filePath pathExtension] isEqualToString:@"txt"]){
[selfperformSegueWithIdentifier:@"txtVC"sender:filePath];
}else{ //目录
MXDocumentsViewController *docvc = [self.storyboardinstantiateViewControllerWithIdentifier:@"fileListTV"];
docvc.path = filePath;
[self.navigationControllerpushViewController: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.identifierisEqualToString:@"pictureVC"]) {
MXPictureViewController *picvc = segue.destinationViewController;
picvc.path = sender;
}elseif ([segue.identifierisEqualToString:@"txtVC"]){
MXTxtViewController *txtvc = segue.destinationViewController;
txtvc.path = sender;
}
}