高级UIKit-03(NSFileManager、NSFileHandle)

时间:2023-03-09 04:52:32
高级UIKit-03(NSFileManager、NSFileHandle)

fileManager文件管理器

【day04_1_FileManager_Search】 :查找文件

fileManager有一个方法可以判断文件是否是文件夹, fileExistsAtPath:isDirectory:这个方法做了两件事情

1.首先判断文件是否存在

2.判断是否是文件夹,并把结果赋给BOOL变量

BOOL isDirectory;

if ([fm fileExistsAtPath:self.path isDirectory:&isDirectory] && isDirectory) { // 如果文件存在并且是文件夹

NSLog(@"是文件夹");

}

递归查找文件的代码

NSFilManager文件管理器本例知识点

需求:在指定的路径里搜索文件

思路:根据FM的一个判断文件是否是目录的方法来解决,并找出查找文件的做的事情,实现递归查找

步骤:

0.写一个递归方法

1.创建FM,使用contentsOfDirectoryAtPath:方法根据路径找出所有文件返回数组

2.循环数组,如果找到文件就copy到指定的文件夹内

3.如果是目录,递归该方法

// 查找文件

-(void)findJpgInDirectoryAtPath:(NSString *)directoryPath{

NSFileManager *fm = [NSFileManager defaultManager];

NSArray *fileNameArray = [fm contentsOfDirectoryAtPath:directoryPath error:nil];

for (NSString *fileName in fileNameArray) {

NSString *filePath = [directoryPath stringByAppendingPathComponent:fileName];

// 找出图片

if ([filePath hasSuffix:@"jpg"]) {

// NSLog(@"%@",filePath);

}

// 搜索图片并拷贝到新文件夹

if (self.findSwitch.isOn) { // 如果是模糊查找

if([filePath rangeOfString:self.findTextField.text].length > 0){

NSString *newPath = [@"/Users/tarena/yz/第三阶段(高级UI)/day04/img" stringByAppendingPathComponent:fileName];

if([fm copyItemAtPath:filePath toPath:newPath error:nil]){

NSLog(@"copy成功");

}

}

}else{

if (!self.findSwitch.isOn) { // 精确查找

if ([self.findTextField.text isEqualToString:[filePath lastPathComponent]]) {

NSString *newPath = [@"/Users/tarena/yz/第三阶段(高级UI)/day04/img" stringByAppendingPathComponent:fileName];

if([fm copyItemAtPath:filePath toPath:newPath error:nil]){

NSLog(@"copy成功");

}

}

}

}

/*

// copy的用法

NSString *srcPath = [directoryPath stringByAppendingPathComponent:@"100785901.jpg"]; // 原文件路径

NSString *destPath = [[directoryPath stringByAppendingPathComponent:@"image"] stringByAppendingPathComponent:@"11.jpg"]; // 目标路径

if ([filePath isEqualToString:srcPath]) {

if ([fm copyItemAtPath:filePath toPath:destPath error:nil]) {

NSLog(@"------copy成功!");

}

}

*/

// remove的用法

/*

if ([filePath isEqualToString:[directoryPath stringByAppendingPathComponent:@"11.jpg"]]) {

if ([fm removeItemAtPath:filePath error:nil]) {

NSLog(@"删除成功!");

}

}

*/

// 递归查找所有目录里的文件

BOOL isDirectory;

if ([fm fileExistsAtPath:filePath isDirectory:&isDirectory] && isDirectory) {

[self findJpgInDirectoryAtPath:filePath];

}

}

}

【day04_2_SystemFile】:系统文件管理器

该案例主要使用了重用VC的功能

// 重用VC

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

MXSystemFileTableViewController *newVC = [self.storyboard instantiateViewControllerWithIdentifier:@"systemFileList"];

NSString *filePath = self.fileArray[indexPath.row];

BOOL isDirectory;

if ([self.fm fileExistsAtPath:filePath isDirectory:&isDirectory] && isDirectory) {

newVC.directoryPath = filePath;

[self.navigationController pushViewController:newVC animated:YES];

}

}

删除功能,删除步骤:

1.先从系统中删除

2.接着从数组模型中删除

3.从界面中移除

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{

if (editingStyle == UITableViewCellEditingStyleDelete) {

// 从系统删除文件

NSFileManager *fm = [NSFileManager defaultManager];

NSString *deleteFilePath = self.fileArray[indexPath.row];

if([fm removeItemAtPath:deleteFilePath error:nil]){

NSLog(@"%@",deleteFilePath);

NSLog(@"删除成功!");

}

// 从数组中删除

[self.fileArray removeObjectAtIndex:indexPath.row];

// 从界面上移除

[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

}

else if (editingStyle == UITableViewCellEditingStyleInsert) {

// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view

}

}

创建文件夹和文件

// 新建文件夹或文件

- (void)addDirectory:(UIBarButtonItem *)sender {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入文件夹名称" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];

alert.alertViewStyle = UIAlertViewStylePlainTextInput; // 设置alert样式为输入框

[alert show];

}

// 实现UIAlertViewDelegate代理方法

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

NSString *directoryName = [alertView textFieldAtIndex:0].text;

NSString *directoryPath = [self.directoryPath stringByAppendingPathComponent:directoryName];

// 如果文件名不包括.就创建目录

if (![directoryName rangeOfString:@"."].length) {

[[NSFileManager defaultManager] createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil];

}

// 创建以.txt .doc结尾的文件

if ([directoryName hasSuffix:@".txt"] || [directoryName hasSuffix:@".doc"]) {

NSString *creatFilePath = [self.directoryPath stringByAppendingPathComponent:directoryName];

[[NSFileManager defaultManager] createFileAtPath:creatFilePath contents:nil attributes:nil];

}

[self.tableView reloadData];

}

保存:

// 保存

- (IBAction)saveAction:(id)sender {

NSFileManager *fm = [NSFileManager defaultManager];

NSData *data = [self.myTextView.text dataUsingEncoding:NSUTF8StringEncoding];

[fm createFileAtPath:self.path contents:data attributes:nil];

[self dismissViewControllerAnimated:YES completion:nil];

}

【day04_3_FileHandle】:NSFileHandle的简单使用read

使用NSFileHandle可以从文件中读取一部分

步骤:

1.创建NSFileHandle对象使用fileHandleForReadingAtPath:path方法并传入path路径

2.设置游标位置

3.读取文件位置,这里两个方法:

readDataOfLength  读取文件到哪个位置,以字节为单位

readDataToEndOfFile 读到最后

这两个方法返回NSData对象,该对象存储的是二进制

NSString *path = @"/Users/...4/images/208718_800x600.jpg";

// 1.创建feileHandle对象

NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:path];

// 获取文件总长度,此时游标在最后

// long long fileLength = fileHandle.seekToEndOfFile; // 获取文件总长度

// 2.设置游标位置

[fileHandle seekToFileOffset:0]; // 设置游标位置

// 3.读取文件

// readDataOfLength  读取文件到哪个位置,以字节为单位

// readDataToEndOfFile 读到最后

NSData *fileData = [fileHandle readDataOfLength:50 * 1024]; // 读取文件

// 4.使用imageWithData方法创建image对象

UIImage *image = [UIImage imageWithData:fileData];

UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];

iv.image = image;

[self.view addSubview:iv];

NSFileHandle的使用案例:

- (void)viewDidLoad

{

[super viewDidLoad];

// 使用NSFileHandle实现打印机打印图片效果

NSString *path = @"/Users/tarena/yz/第三阶段(高级UI)/day04/images/208718_800x600.jpg";

// 创建NSFileHandle并设置读取路径

self.readFH = [NSFileHandle fileHandleForReadingAtPath:path];

// [self.readFH seekToFileOffset:0]; // 游标默认位置就是0

self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];

[self.view addSubview:self.imageView];

self.data = [NSMutableData data]; // 初始化data

// 使用定时器来实现这个效果

self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(readFileData:) userInfo:nil repeats:YES];

}

-(void)readFileData:(NSTimer *)timer{

NSData *subData = [self.readFH readDataOfLength:1024]; // 每次读取1K数据

[self.data appendData:subData]; // 把数据追加到data中

UIImage *image = [UIImage imageWithData:self.data]; // 从data中获取数据

self.imageView.image = image;

NSLog(@"%d",subData.length);

if (subData.length == 0) { // 如果读完就停掉计时器,读完的标志就是subData.length == 0

[self.timer invalidate];

}

}

【day04_4_FileHandleWrite】:NSFileHandle的write操作

使用fileHandle写数据

步骤:

1.读取要写入的数据

2.创建文件

3.写数据到创建的文件中

- (void)viewDidLoad

{

[super viewDidLoad];

// fileHandle写数据

// 写数据之前

// 1.先读取数据

NSString *path = @"/Users/tarena/yz/第三阶段(高级UI)/day04/images/13_0.jpg";

self.readFH = [NSFileHandle fileHandleForReadingAtPath:path];

// 2.然后创建文件

NSString *writePath = @"/Users/tarena/yz/第三阶段(高级UI)/day04/images/c.jpg";

[[NSFileManager defaultManager] createFileAtPath:writePath contents:nil attributes:nil];

// 3.写数据,创建NSFileHandle对象并使用write方法设置路径

self.writeFH = [NSFileHandle fileHandleForWritingAtPath:writePath];

// 使用计时器写入数据

self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(writeDataToJpg) userInfo:nil repeats:YES];

}

-(void)writeDataToJpg{

NSData *data = [self.readFH readDataOfLength:10*1024];

[self.writeFH writeData:data]; // 调用writeData方法写入数据

if (data.length == 0) {

[self.writeFH closeFile]; // 关闭文件

[self.timer invalidate]; // 停掉计时器

}

}