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]; // 停掉计时器

}

}

高级UIKit-03(NSFileManager、NSFileHandle)的更多相关文章

  1. Spring学习笔记-高级装配-03

    主要内容: ●Spring profile ●条件化的bean声明 ●自动装配与歧义性 ● Spring表达式语言 本章介绍一些高级的装配技术,可实现更为高级的装配功能. 环境与profile 软件开 ...

  2. Linux高级编程--03.make和makfile

    Makefile语法基础 在Linux下,自动化编译工具是通过make命令来完成的(一些工具厂商也提供了它们自己的make命令,如gmake等),make命令的基本格式如下: make [-f mak ...

  3. Java入门 - 高级教程 - 03.泛型

    原文地址:http://www.work100.net/training/java-generic.html 更多教程:光束云 - 免费课程 泛型 序号 文内章节 视频 1 概述 2 泛型方法 3 泛 ...

  4. 03 flask源码剖析之threading.local和高级

    03 threading.local和高级 目录 03 threading.local和高级 1.python之threading.local 2. 线程唯一标识 3. 自定义threading.lo ...

  5. javaScript高级含Es6

    JavaScript高级第01天笔记 1.面向过程与面向对象 1.1面向过程 面向过程就是分析出解决问题所需要的步骤,然后用函数把这些步骤一步一步实现,使用的时候再一个一个的依次调用就可以了. 1.2 ...

  6. 李洪强iOS经典面试题153- 补充

    李洪强iOS经典面试题153- 补充   补充 有空就来解决几个问题,已经懒癌晚期没救了... UML 统一建模语言(UML,UnifiedModelingLanguage)是面向对象软件的标准化建模 ...

  7. JAVA EE企业级开发四步走完全攻略 [转]

    http://bbs.51cto.com/thread-550558-1.html 本文是J2EE企业级开发四步走完全攻略索引,因内容比较广泛,涉及整个JAVA EE开发相关知识,这是一个长期的计划, ...

  8. Swift - 给表格添加编辑功能(删除,插入)

    1,下面的样例是给表格UITableView添加编辑功能: (1)给表格添加长按功能,长按后表格进入编辑状态 (2)在编辑状态下,第一个分组处于删除状态,第二个分组处于插入状态 (3)点击删除图标,删 ...

  9. Swift - 给表格的单元格UITableViewCell添加图片,详细文本标签

    表格UITableView中,每一单元格都是一个UITableViewCell.其支持简单的自定义,比如在单元格的内部,添加图片和详细文本标签. 注意UITableViewCell的style: (1 ...

  10. Swift - 使用表格组件(UITableView)实现分组列表

    1,样例说明: (1)列表以分组的形式展示 (2)同时还自定义分区的头部和尾部 (3)点击列表项会弹出消息框显示该项信息. 2,效果图:       3,代码如下: 1 2 3 4 5 6 7 8 9 ...

随机推荐

  1. c 有关N!阶乘的相关问题----陆续补充上来

    第一个:求N!结果中末尾0的个数问题.思路是末尾0的产生   5*偶数,阶乘中偶数的个数肯定比5多,所以求出阶乘中5的个数就可以求出末尾0的个数. #include<stdio.h> in ...

  2. C#直接插入排序

    以Int类型数组为举例 namespace 直接插入排序 { class Program { private static void Insert(int[] arrayList) { bool is ...

  3. codeforces 559A(Gerald's Hexagon)

    Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u   Description Gera ...

  4. mac下面xcode+ndk7配置cocos2dx & box2d的跨ios和android平台的游戏教程

    这篇教程是介绍如何使用cocos2d-x和box2d来制作一个demo,且此demo能同时运行于ios和android平台.在继续阅读之前,建议您先阅读上一篇教程. 首先,按照上一篇教程,搭建好mac ...

  5. TortoiseSVN和Eclipse中subversion无法协同使用

    环境: Eclipse版本Luna, 第一次安装subversion插件时, 使用了http://download.eclipse.org/releases/luna中的Subversive, 版本为 ...

  6. 405 HTTP method GET is not supported by this URL

    孙鑫java web开发详解P285里面提交Get网站弹出提示405 HTTP method GET is not supported by this URL 原因父类doGet()方法未覆盖. 应写 ...

  7. Web Api Route 注册要放在 Mvc Route 注册前

    今天想研究一下Web Api,写了一个测试Api,打开网站后浏览一下,可是却提示找不到方法,刚开始以为哪里配置错了,可找了半天也没见. 因为我是在一个现有Mvc站点做的Demo,所以打算新建一个Mvc ...

  8. C++一些注意点之异常处理

    几篇文章:(1)http://blog.csdn.net/daheiantian/article/details/6530318 (2)http://blog.chinaunix.net/uid-21 ...

  9. CodeForces - 27E--Number With The Given Amount Of Divisors(反素数)

    CodeForces - 27E Number With The Given Amount Of Divisors Submit Status Description Given the number ...

  10. UVA 270 Lining Up 共线点 暴力

    题意:给出几个点的位置,问一条直线最多能连过几个点. 只要枚举每两个点组成的直线,然后找直线上的点数,更新最大值即可. 我这样做过于暴力,2.7s让人心惊肉跳...应该还能继续剪枝的,同一直线找过之后 ...