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. mysql待整理

    1. MYSQL SQL_NO_CACHE的真正含义 http://www.dewen.org/q/5149/Mysql 是 结果不缓存,但查询还是缓存了. 如果要重新测试,就在查询前先执行一下&qu ...

  2. C# Code Snip

    1.Tryf + TAB+TAB try { } finally { } 2.Prop+Tab+Tab public int MyProperty { get; set; } 3. #region + ...

  3. mysql 中的 IF 和 IFNULL 用法

    IFNULL(expr1,expr2) 如果expr1不是NULL,IFNULL()返回expr1,否则它返回expr2.IFNULL()返回一个数字或字符串值,取决于它被使用的上下文环境. IF(S ...

  4. js中设置setInterval的注意点

    <html> <head> <meta http-equiv="Content-Type" content="text/html; char ...

  5. Yii2 composer win7安装新建项目流程

    一.首先下载 Composer-Setup.exe ,安装. 问题1:openSSL 问题,在php.ini  内去掉":"注释 问题2:browscap 问题 ,在php.ini ...

  6. 解决ASP.NET回传后div滚动条位置复位的问题

    中心思想:用一个隐藏控件保存当前scorll值.回传回来后根据scrollTop的值,然后在Page_Load中重新设置scrollTop. 首先是为DIV添加一个 onscroll="ja ...

  7. repeater一个简单的用法例子

    (前台) <asp:Repeater ID="Repeater1" runat="server"       onitemdatabound=" ...

  8. Android Dalvik 虚拟机

    简介 Android 平台虽然是使用java语言来开发应用程序,但Android程序却不是运行在标准java虚拟机上的.谷歌专门为Android平台设计了一套虚拟机来运行Android程序.它就是Da ...

  9. 「JAVA」:Berkeley DB的JAVA连接

    Berkeley DB是一个嵌入式的数据库,它适合于管理海量的.简单的数据.关键字/数据(key/value)是Berkeley DB用来进行数据管理的基础.每个key/value构成了一条记录,而整 ...

  10. POJ 1410 Intersection(线段相交&amp;&amp;推断点在矩形内&amp;&amp;坑爹)

    Intersection 大意:给你一条线段,给你一个矩形,问是否相交. 相交:线段全然在矩形内部算相交:线段与矩形随意一条边不规范相交算相交. 思路:知道详细的相交规则之后题事实上是不难的,可是还有 ...