1、文件管理器(NSFileManager)

 1> 主要作用及功能方法

  • 主要作用:此类主要是对文件进行的操作(创建/删除/改名等)以及文件信息的获取。

  • 功能方法:

 2> 创建文件夹

  创建所需的方法在头文件的声明:

/* createDirectoryAtPath:withIntermediateDirectories:attributes:error: creates a directory at the specified path. If you pass 'NO' for createIntermediates, the directory must not exist at the time this call is made. Passing 'YES' for 'createIntermediates' will create any necessary intermediate directories. This method returns YES if all directories specified in 'path' were created and attributes were set. Directories are created with attributes specified by the dictionary passed to 'attributes'. If no dictionary is supplied, directories are created according to the umask of the process. This method returns NO if a failure occurs at any stage of the operation. If an error parameter was provided, a presentable NSError will be returned by reference.

    This method replaces createDirectoryAtPath:attributes:
*/
// 参数1:创建的文件夹的路径
// 参数2:是否创建媒介的布尔值,一般为YES
// 参数3: 属性,没有就置为nil
// 参数4: 错误信息
- (BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(nullable NSDictionary<NSString *, id> *)attributes error:(NSError **)error NS_AVAILABLE(10_5, 2_0);

  实例代码:

    // 创建对象
NSFileManager *manager = [NSFileManager defaultManager];
// 创建路径
NSString *path = NSHomeDirectory(); path = [path stringByAppendingPathComponent:@"test/myApp"]; NSLog(@"%@", path); NSError *error = nil; // 创建文件夹
BOOL success = [manager createDirectoryAtPath:path
withIntermediateDirectories:YES
attributes:nil
error:&error];
NSLog(@"success = %d,error = %@", success,error);

 2> 向文件夹中添加文件

  内容写入方法在头文件的声明:

// 参数1:要写入内容的文件的文件路径
// 参数2:一个BOOL值,一般为YES
// 参数3: 编码方式,一般为UTF8
// 参数4:错误信息
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error;

  实例代码:

    //向文件夹中添加字符串
path = [path stringByAppendingPathComponent:@"zifucuan.txt"]; //初始化一个字符串
NSString *string = @"hello"; BOOL success1 = [string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil]; if (success1) { NSLog(@"成功:%@",path);
}else{
NSLog(@"失败");
}

 3> 删除文件夹中文件

  删除文件方法在头文件的声明:

// 参数1:路径
// 参数2:错误信息
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error NS_AVAILABLE(10_5, 2_0);

  实例代码:

    // 删除path目录下的所有文件
[manager removeItemAtPath:path error:nil];

 4> 文件移动

  文件移动方法在头文件的声明:

// 参数1:要移动的文件路径
// 参数2:要移动到的文件路径(目的地)
// 参数3:错误信息
- (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error NS_AVAILABLE(10_5, 2_0);

  实例代码:

    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:];

    // 创建一个文件夹
NSString *copyPath = [documentPath stringByAppendingPathComponent:@"备份/test.txt"]; // stringByDeletingLastPathComponent 删除最后一个路径
[manager createDirectoryAtPath:[copyPath stringByDeletingLastPathComponent]
withIntermediateDirectories:YES
attributes:nil
error:nil];
// 定义一个字符串
NSString *testStr = @"Hello World"; NSData *data = [testStr dataUsingEncoding:NSUTF8StringEncoding]; // 将内容写入文件
[manager createFileAtPath:copyPath
contents:data
attributes:nil]; // 创建一个toPath
NSString *toPath = [documentPath stringByAppendingPathComponent:@"hello/copyTest.txt"]; // 创建一个移动到的文件夹及文件
[manager createDirectoryAtPath:[toPath stringByDeletingLastPathComponent]
withIntermediateDirectories:YES
attributes:nil
error:nil]; BOOL result = [manager moveItemAtPath:copyPath
toPath:toPath
error:nil];
NSLog(@"result = %d", result);

 5> 文件copy(拷贝)

  文件copy(拷贝)方法在头文件的声明:

// 参数1:要拷贝的文件路径 
// 参数2:要拷贝到的文件路径(目的地)
// 参数3:错误信息
- (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error NS_AVAILABLE(10_5, 2_0);

  实例代码:

// 路径使用上面的路径
[manager copyItemAtPath:copyPath
toPath:toPath
error:nil];

2、文件夹处理器(NSFileHandle)

 1> 概述

  • NSFileHandle 是非常基础的只针对文件内容的操作(写入,读取,更新),是把NSData,通过连接器一个字节一个字节的写入/读取文件.(NSData <—> NSFileHandle <—> 文件).

  • 使用场景: 对文件内容的进行局部修改、追加内容。

  • 使用步骤

 1).文件对接并获取一个NSFileHandle对象.

 2).读写操作

     3).关闭对接

  注意:NSFileHandle 类并没有提供创建文件的功能。必须使用 NSFileManager 方法来创建文件。因此,在使用下图表中的方法时,都是保证文件已经存在,否则返回nil.

 2> 功能方法

 3> 使用NSFileHandle向文件夹追加内容

  • 通过fileHandle更新
// 参数为文件路径
+ (nullable instancetype)fileHandleForUpdatingAtPath:(NSString *)path;
  • 搜索到文本内容末尾方法
// 搜索到文件内容的末尾
- (unsigned long long)seekToEndOfFile;
  • 实例代码:(使用上面的路径)
    // 创建handle对象
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:path]; // 搜索到文本内容末尾
[fileHandle seekToEndOfFile]; NSString *appendStr = @"我是后来的"; NSData *appendData = [appendStr dataUsingEncoding:NSUTF8StringEncoding]; // 将数据写入到对接起
[fileHandle writeData:appendData]; // 关闭对接起
[fileHandle closeFile];

 4> 定位数据

  • 通过fileHandle读取
// 参数为文件路径
+ (nullable instancetype)fileHandleForReadingAtPath:(NSString *)path;
  • 获取文件中可获得的数据(所有数据)
@property (readonly, copy) NSData *availableData;
  • 设置文件的偏移量
// 参数为一个和文件长度有关的数值
- (void)seekToFileOffset:(unsigned long long)offset;
  • 从文件的偏移量位置读取到最后
- (NSData *)readDataToEndOfFile;

实例代码:

    // 将“123456”写入file2.txt文件夹中
NSString * content = @"";
NSString * filePath2 = [documentPath stringByAppendingPathComponent:@"file2.txt"];
[fileManager createFileAtPath:filePath2 contents:[content dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]; // 通过fileHandle读取
fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath2];
// 获取数据长度
NSUInteger length = [[fileHandle availableData] length];
// 设置文件的偏移量为文件的一半
[fileHandle seekToFileOffset:length/2.0];
// 从文件的偏移量位置读取到最后
NSData * data = [fileHandle readDataToEndOfFile];
[fileHandle closeFile];
// 打印读取的字符串
NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",string);

【原】iOS学习之文件管理器(NSFileManager)和文件对接器(NSFileHandle)的更多相关文章

  1. UI进阶 文件管理器(NSFileManager)文件对接器(NSFileHandle)

    一.文件管理器与文件连接器之间的区别 文件管理器(NSFileManager) 此类主要是对文件进行的操作(创建/删除/改名等)以及文件信息的获取. 文件连接器(NSFileHandle) 此类主要是 ...

  2. 归档NSKeyedArchiver解归档NSKeyedUnarchiver与文件管理类NSFileManager (文件操作)

    ========================== 文件操作 ========================== 一.归档NSKeyedArchiver 1.第一种方式:存储一种数据. // 归档 ...

  3. 【原】iOS学习之ARC和非ARC文件混编

    在编程过程中,我们会用到很多各种各样的他人封装的第三方代码,但是有很多第三方都是在非ARC情况下运行的,当你使用第三方编译时出现和下图类似的错误,就说明该第三方是非ARC的,需要进行一些配置.

  4. iOS 学习 - 23 加载本地 txt 文件, NSMutableParagraphStyle 段落格式,缩放动画,字体间距

    思路: 1.new 一个 Empty 后缀为 .txt 文件,内容随笔拷贝一段 2.用 NSString 接收本地文件,再用一个标题拼接字符串 3.创建一个 NSMutableParagraphSty ...

  5. 02-IOSCore - NSFileHandle、合并文件、文件指针、文件查看器

    [day0201_NSFileHandle]:文件句柄 1 NSFileHandle 文件对接器.文件句柄 常用API: - (NSData *)readDataToEndOfFile;读取数据到最后 ...

  6. Qt Quick综合实例之文件查看器

    假设你基于Qt SDK 5.3.1来创建一个Qt Quick App项目,项目模板为你准备的main.qml文档的根元素是ApplicationWindow或Window.这次我们就以Applicat ...

  7. 自定义Yaml解析器替换Properties文件

    自定义Yaml解析器替换Properties文件 项目结构 案例代码 配置类SpringConfiguration @Configuration @Import(JdbcCofnig.class) @ ...

  8. iOS学习之iOS沙盒(sandbox)机制和文件操作之NSFileManager(三)

    1.在Documents里创建目录 创建一个叫test的目录,先找到Documents的目录, NSArray *paths = NSSearchPathForDirectoriesInDomains ...

  9. 原 iOS深入学习(Block全面分析)http://my.oschina.net/leejan97/blog/268536

    原 iOS深入学习(Block全面分析) 发表于1年前(2014-05-24 16:45)   阅读(26949) | 评论(14) 39人收藏此文章, 我要收藏 赞21 12月12日北京OSC源创会 ...

随机推荐

  1. 在linux终端远程登陆linux服务器

    在linux终端远程登陆linux服务器   原来在Linux终端远程登陆linux服务器是那么的容易,如果的服务器用户名是abc(也可以是root),只需要在终端输入: 然后电脑会提示输入密码就登录 ...

  2. AFNetworking certificate AFNetworking 证书设置

    + (AFSecurityPolicy*)customSecurityPolicy { // /先导入证书 NSString *cerPath = [[NSBundle mainBundle] pat ...

  3. 关于学习angularJS 的 心里路程(二)

    这一次主要的学习内容是 ng-route(本次的项目由于种种原因吧,我们采用了ui-router,而不是原生的ng-route) * 配置路由. * 注意这里采用的是ui-router这个路由,而不是 ...

  4. jQuery如何判断元素是否是隐藏的?

    jQuery函数简介: is(expr) 用一个表达式来检查当前选择的元素集合,如果其中至少有一个元素符合这个给定的表达式就返回true. 如果没有元素符合,或者表达式无效,都返回'false'. 注 ...

  5. PHP判断文件或者目录是否可写

    在PHP中,可用is_writable()函数来判断一个 文件/目录 是否可写,详情如下: 参考 is_writable (PHP 4, PHP 5) is_writable — 判断给定的文件名是否 ...

  6. 动态执行python脚本

    前言 存在许多独立的python脚本,这些脚本可能会增加,也可能会减少,现在需要按照某种顺序调度这些程序.在python的standard library中,有一个模块imp可以实现动态的调用ptho ...

  7. C# 使用 StructLayoutAttribute 时 C# /C++ 内存空间分配与成员对齐问题

    1. 使用场景 公共语言运行时控制数据字段的类或结构在托管内存中的物理布局.但是,如果想要将类型传递到非托管代码,需要使用 StructLayout 属性. 2. 内存分配问题. 如果不显示的设置内存 ...

  8. Socket通信(一)

    代码及PDF下载链接:http://download.csdn.net/detail/u010312811/9683034 例程1:实现服务器与客户端的连接与简单数据收发 参考链接:http://bl ...

  9. Eclipse关闭XML文件验证的方法

    XML的编写是否符合规范,可以通过XML Schema或DTD进行验证,但有时候电脑本来就很卡,而且XML的某些错误并未导致程序无法运行的情况下,暂时关闭XML的验证也算不错的选择. 如web.xml ...

  10. iOS 4种开发者身份的官方说明

    https://developer.apple.com/support/compare-memberships/cn/ 为了防止链接失效,截图如下: