一、介绍

利用NSFilehandle类提供的方法,允许更有效地使用文件。

一般而言,处理文件时都要经历以下三个步骤:

1.打开文件,并获取一个NSFileHandle对象,以便在后面的I/O操作中引用该文件

2.对打开的文件执行I/O操作(读取、写入、更新)

3.关闭文件

注意:

NSFileHandle  此类主要对文件内容进行读取和写入操作,可以使用NSFileHandle做文件的断点续传。

NSFileManger 此类主要是对文件进行的操作以及文件信息的获取

 

二、API

NSFileManger:

-(NSData *)contentsAtPath:path                                         //从一个文件读取数据

-(BOOL)createFileAtPath: path contents:(NSData *)data attributes:attr  //向一个文件写入数据(能否写入由其attributes决定)

-(BOOL)removeItemAtPath:path error:err                                 //删除一个文件

-(BOOL)moveItemAtPath:from toPath:to error:err                        //重命名或者移动一个文件(to不能是已存在的)

-(BOOL)copyItemAtPath:from toPath:to error:err                         //复制文件(to不能是已存在的)

-(BOOL)contentsEqualAtPath:path andPath:path2                          //比较两个文件的内容

-(BOOL)fileExistAtPath:path                                       //测试文件是否存在

-(BOOL)isReadableFileAtPath:path                                 //测试文件是否存在,并且是否能执行读操作  

-(BOOL)isWriteableFileAtPath:path                                //测试文件是否存在,并且是否能执行写操作  

-(NSDictionary *)attributesOfItemAtPath:path error:err            //获取文件的属性  

-(BOOL)setAttributesOfItemAtPath:attr error:err                  //更改文件的属性

NSFileHandle:

+ (id)fileHandleForReadingAtPath:(NSString *)path     //打开一个文件准备读取

+ (id)fileHandleForWritingAtPath:(NSString *)path     //打开一个文件准备写入 

+ (id)fileHandleForUpdatingAtPath:(NSString *)path     //打开一个文件准备更新

- (NSData *)availableData;                   //从设备或通道返回可用的数据 

- (NSData *)readDataToEndOfFile;               //从当前的节点读取到文件的末尾 

- (NSData *)readDataOfLength:(NSUInteger)length;      // 从当前节点开始读取指定的长度数据 

- (void)writeData:(NSData *)data;                //写入数据 

- (unsigned long long)offsetInFile;              //获取当前文件的偏移量 

- (void)seekToFileOffset:(unsigned long long)offset;     //跳到指定文件的偏移量 

- (unsigned long long)seekToEndOfFile;            //跳到文件末尾 

- (void)truncateFileAtOffset:(unsigned long long)offset; //将文件的长度设为offset字节

- (void)closeFile;                         //关闭文件

三、使用

NSFileManger基本用法: 文件创建

//初始化一个NSFileManager类defaultManager方法为单例模式,通过单例模式进行初始化
NSFileManager * fileManager =[NSFileManager defaultManager]; //拼接路径
NSString * path=NSHomeDirectory();
path=[path stringByAppendingPathComponent:@"deskTop/date.txt"]; //创建文件
BOOL flag=[fileManager createFileAtPath:path contents:nil attributes:nil];
if(flag){
NSLog(@"文件创建成功");
}else{
NSLog(@"文件创建失败");
}

NSFileManger基本用法: 目录创建

NSFileManager  * fileManager =[NSFileManager defaultManager];
NSString * path=NSHomeDirectory();
path=[path stringByAppendingPathComponent:@"deskTop/pro/cpp"];
BOOL flag=[fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
if(flag){
NSLog(@"创建成功");
}else{
NSLog(@"创建失败");
}

NSFileManger基本用法: 文件/目录删除

NSFileManager  * fileManager =[NSFileManager defaultManager];
NSString * rootPath=NSHomeDirectory();
NSString * dirPath=[rootPath stringByAppendingPathComponent:@"deskTop/newFolder"];
NSArray * array=[fileManager contentsOfDirectoryAtPath:dirPath error:nil];
for(NSString * str in array){
NSString * newPath=[dirPath stringByAppendingPathComponent:str];
BOOL flag=[fileManager removeItemAtPath:newPath error:nil];
if(flag){
NSLog(@"删除成功");
}else{
NSLog(@"删除失败");
}
}

NSFileManger基本用法: 复制或者移动文件

//将一个文件复制到另一个文件
[fileManager copyItemAtPath:path1 toPath:path2 error:nil]; //将一个文件移动到另一个文件
[fileManager moveItemAtPath:path1 toPath:path2 error:nil]; //获取文件里面的内容
NSData * readData=[fileManager contentsAtPath:path]

NSFileHandle基本用法:  追加数据

 NSString *homePath  = NSHomeDirectory( );
NSString *sourcePath = [homePath stringByAppendingPathConmpone:@"testfile.text"];
NSFileHandle *fielHandle = [NSFileHandle fileHandleForUpdatingAtPath:sourcePath];
[fileHandle seekToEndOfFile]; //将节点跳到文件的末尾
NSString *str = @"追加的数据"
NSData* stringData = [str dataUsingEncoding:NSUTF8StringEncoding];
[fileHandle writeData:stringData]; //追加写入数据
[fileHandle closeFile];

NSFileHandle基本用法:  定位数据

 NSFileManager *fm = [NSFileManager defaultManager];
NSString *content = @"abcdef";
[fm createFileAtPath:path contents:[content dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
NSUInteger length = [fileHandle availabelData] length];// 获取数据长度
[fileHandle seekToFileOffset;length/]; //偏移量文件的一半
NSData *data = [fileHandle readDataToEndOfFile];
[fileHandle closeFile];

NSFileHandle基本用法:  复制文件

NSFileHandle *infile, *outfile;   //输入文件、输出文件
NSData *buffer; //读取的缓冲数据
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *homePath = NSHomeDirectory( );
NSString *sourcePath = [homePath stringByAppendingPathComponent:@"testfile.txt"]; // 源文件路径
NSString *outPath = [homePath stringByAppendingPathComponent:@"outfile.txt"]; //输出文件路径
BOOL sucess = [fileManager createFileAtPath:outPath contents:nil attributes:nil];
if (!success)
{
return N0;
}
infile = [NSFileHandle fileHandleForReadingAtPath:sourcePath]; //创建读取源路径文件
if (infile == nil)
{
return NO;
}
outfile = [NSFileHandle fileHandleForReadingAtPath:outPath]; //创建并打开要输出的文件
if (outfile == nil)
{
return NO;
}
[outfile truncateFileAtOffset:]; //将输出文件的长度设为0
buffer = [infile readDataToEndOfFile]; //读取数据
[outfile writeData:buffer]; //写入输入
[infile closeFile]; //关闭写入、输入文件
[outfile closeFile];

 

四、实例演示

通过一个句柄,将语音识别的音频写入文件

//创建句柄
- (void)configFileHandler:(NSString *)fileName {
self.fileHandler = [self createFileHandleWithName:fileName isAppend:NO];
} - (NSFileHandle *)createFileHandleWithName:(NSString *)aFileName isAppend:(BOOL)isAppend {
NSFileHandle *fileHandle = nil;
NSString *fileName = [self getFilePath:aFileName]; int fd = -;
if (fileName) {
if ([[NSFileManager defaultManager] fileExistsAtPath:fileName]&& !isAppend) {
[[NSFileManager defaultManager] removeItemAtPath:fileName error:nil];
} int flags = O_WRONLY | O_APPEND | O_CREAT;
fd = open([fileName fileSystemRepresentation], flags, );
} if (fd != -) {
fileHandle = [[NSFileHandle alloc] initWithFileDescriptor:fd closeOnDealloc:YES];
}
return fileHandle;
} //存储音频
#pragma mark - MVoiceRecognitionClientDelegate
- (void)VoiceRecognitionClientWorkStatus:(int)workStatus obj:(id)aObj { switch (workStatus) {
case EVoiceRecognitionClientWorkStatusNewRecordData: {
/// 录音数据回调、NSData-原始音频数据,此处可以用来存储录音
NSData *originData = (NSData *)aObj;
[self.mutabelData appendData:originData];
break;
}
case EVoiceRecognitionClientWorkStatusStartWorkIng: {
/// 识别工作开始,开始采集及处理数据
break;
}
case EVoiceRecognitionClientWorkStatusStart: {
/// 检测到用户开始说话
break;
}
case EVoiceRecognitionClientWorkStatusFlushData: {
/// 连续上屏、NSDictionary-中间结果
break;
}
case EVoiceRecognitionClientWorkStatusFinish: {
/// 语音识别功能完成,服务器返回正确结果、最终识别结果
break;
}
case EVoiceRecognitionClientWorkStatusError: {
/// 发生错误 NSError-错误信息
break;
}
case EVoiceRecognitionClientWorkStatusLongSpeechEnd: {
/// 长语音结束状态
[self endLongSpeechRecognition];
break;
}
default:
break;
}
} //写入音频
- (void)endLongSpeechRecognition{
//关闭识别服务
[self.asrEventManager sendCommand:BDS_ASR_CMD_STOP];
[self.fileHandler writeData:self.mutabelData];
self.mutabelData = nil;
} //懒加载
-(NSMutableData *)mutabelData{
if (!_mutabelData) {
_mutabelData = [NSMutableData data];
}
return _mutabelData;
}

五、文章引用

原文链接:https://www.jianshu.com/p/8249e3abcd4a

原文链接:http://www.cnblogs.com/jerehedu/

iOS:NSFileHandle和NSFileManger的使用的更多相关文章

  1. IOS的XML文件解析,利用了NSData和NSFileHandle

    如果需要了解关于文档对象模型和XML的介绍,参看 http://www.cnblogs.com/xinchrome/p/4890723.html 读取XML 上代码: NSFileHandle *fi ...

  2. IOS之NSFileManager 和NSFileHandle

    在现阶手机app的临时缓存文件渐渐增多,在app开发中对于移动设备文件的操作越来越多,我们IOS中对于文件的操作主要涉及两个类NSFileManager 和NSFileHandle,下面我们就看看如何 ...

  3. 【原】iOS学习之文件管理器(NSFileManager)和文件对接器(NSFileHandle)

    1.文件管理器(NSFileManager) 1> 主要作用及功能方法 主要作用:此类主要是对文件进行的操作(创建/删除/改名等)以及文件信息的获取. 功能方法: 2> 创建文件夹 创建所 ...

  4. ios NSFileManager和NSFileHandle(附:获取文件大小 )

    转自 http://blog.csdn.net/zhibudefeng/article/details/7795946 //file 文件操作 NSFileManager  常见的NSFileMana ...

  5. iOS开发——网络篇——文件下载(NSMutableData、NSFileHandle、NSOutputStream)和上传、压缩和解压(三方框架ZipArchive),请求头和请求体格式,断点续传Range

    一.小文件下载 NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion ...

  6. 读取和写入 文件 (NSFIleManger 与 NSFileHandle)

    读取和写入 文件 //传递文件路径方法 -(id)initPath:(NSString *)srcPath targetPath:(NSString *)targetPath { self = [su ...

  7. IOS文件系统及其相关操作(NSFileManager,NSFileHandle)

    How do you get the paths to these special sandbox directories? NSArray *NSSearchPathForDirectoriesIn ...

  8. iOS中的下载管理器(支持断点续传)

    在空闲时间自己编写了一个简单的iOS下载管理器.该管理器实现如下功能: 1.能够支持正常的下载,暂停,继续操作. 2.支持断点续传,实现暂停执行继续操作后,依然能正常将文件下载完成. 3.实现实时状态 ...

  9. iOS开发系列--网络开发

    概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博.微信等,这些应用本身可能采用iOS开发,但是所有的数据支撑都是基于后台网络服务器的.如今,网络编程越来越普遍,孤立的应用通常是没有生命力 ...

随机推荐

  1. Ant+Jmeter自动化接口测试的部署 及 部署过程中的坑

    一.环境准备: 1.Jdk1.6或以上:http://www.oracle.com/technetwork/java/javase/downloads/index.html    配置环境变量-系统变 ...

  2. js常用函数整理

    类型转换:parseInt\parseFloat\toString 类型判断:typeof;eg:if(typeof(var)!="undefined")\isNaN 字符处理函数 ...

  3. JavaScript对象简介(一)

    本节介绍js的9个对象:Array数组对象 Boolean(true false) Date日前对象 Math 数学对象 Number 数字对象 String 字符串对象 RegExp 正则表达式对象 ...

  4. Python 定值类

    1.__str__和__repr__ 如果要把一个类的实例变成 str,就需要实现特殊方法__str__(): class Person(object): def __init__(self, nam ...

  5. iOS学习笔记之触摸事件&UIResponder

    iOS学习笔记之触摸事件&UIResponder 触摸事件 与触摸事件相关的四个方法如下: 一根手指或多根手指触摸屏幕 -(void)touchesBegan:(NSSet *)touches ...

  6. Paget Object 设计模式编写selenium测试用例

    示例常规代码 baidu.py # _*_ coding:utf-8 _*_ import csv,unittest,time #导入csv模块 from time import sleep from ...

  7. 检测cpu、主板、内存

    https://jingyan.baidu.com/article/636f38bb595cebd6b84610eb.html

  8. day14--前端HTML、CSS

        HTML是一个裸体的人,CSS穿上华丽的衣服,JS动起来.     HTML 1. -一套规则,浏览器识别的规则 2. 开发者: 学习HTML规则 开发后台程序 - 写HTML文件(充当模板的 ...

  9. 转载 c++指针 指针入门

    这是一篇我所见过的关于指针的最好的入门级文章,它可使初学者在很短的时间内掌握复杂的指针操作.虽然,现在的Java.C#等语言已经取消了指针,但作为一个C++程序员,指针的直接操作内存,在数据操作方面有 ...

  10. (转)细说JDK动态代理的实现原理

    原文:http://blog.csdn.net/mhmyqn/article/details/48474815 关于JDK的动态代理,最为人熟知的可能要数Spring AOP的实现,默认情况下,Spr ...