iOS开发之OC篇(7)——NSFileHandle文件操作对象

版本

Xcode 8.2.1

前文介绍了NSFileManager文件管理器,今天来讲讲NSFileHandle文件操作对象。这两个有什么区别呢?

  • NSFileMange 此类主要是对文件进行的操作(移动、复制、修改、删除等)以及文件信息的获取
  • NSFileHandle 此类主要是对文件内容进行读取和写入操作

创建了NSFileHandle类和实例对象,我们先按command点击NSFileHandle这个类,看看它都有些什么方法。因为方法不太多,索性都列出来吧~

1、NSFileHandle类方法(+方法)

//打开Path对应文件准备读取,或者说打开读取权限。(返回该文件对应的NSFileHandle,以下+方法均同)
+(nullable instancetype)fileHandleForReadingAtPath:(NSString *)path;    
//打开Path对应文件准备写入
+(nullable instancetype)fileHandleForWritingAtPath:(NSString *)path;    
//打开Path对应文件准备更新
+(nullable instancetype)fileHandleForUpdatingAtPath:(NSString *)path;
//打开URL地址对应文件准备读取   
+(nullable instancetype)fileHandleForReadingFromURL:(NSURL *)url error:(NSError **)error;   
//打开URL地址对应文件准备写入
+(nullable instancetype)fileHandleForWritingToURL:(NSURL *)url error:(NSError **)error; 
//打开URL地址对应文件准备更新
+(nullable instancetype)fileHandleForUpdatingURL:(NSURL *)url error:(NSError **)error;

注: (nullable instancetype)为Xcode 6.3的新特性nullability annotations,在这里表示这个对象可以是空对象。

2、NSFileHandle对象方法(-方法)

//读取文件所有数据,从游标(指针)位置(第一次读取在文件起始位置)读到文件末尾
- (NSData *)readDataToEndOfFile;
//从当前节点开始读取指定的长度数据
- (NSData *)readDataOfLength:(NSUInteger)length;
//从当前节点开始写入数据
- (void)writeData:(NSData *)data;

//移动游标到末尾
- (unsigned long long)seekToEndOfFile;
//移动游标到指定位置(offset偏移量)
- (void)seekToFileOffset:(unsigned long long)offset;

//将文件长度截取为offset字节。如多余,填空
- (void)truncateFileAtOffset:(unsigned long long)offset;
//同步文件
- (void)synchronizeFile;
//关闭文件
- (void)closeFile;

//通过文件描述符创建一个NSFileHandle对象
- (instancetype)initWithFileDescriptor:(int)fd closeOnDealloc:(BOOL)closeopt;
//使用解码器,将二进制数据流解码成NSFileHandle对象
- (nullable instancetype)initWithCoder:(NSCoder *)coder;

//在后台读取文件,完成后发出通知
- (void)readInBackgroundAndNotifyForModes:(nullable NSArray<NSRunLoopMode> *)modes;
//在当前线程操作完成同上动作
- (void)readInBackgroundAndNotify;

//与readInBackgroundAndNotifyForModes类似,读完
- (void)readToEndOfFileInBackgroundAndNotifyForModes:(nullable NSArray<NSRunLoopMode> *)modes;
//在当前线程操作完成同上动作
- (void)readToEndOfFileInBackgroundAndNotify;

//在后台接收连接,完成后通知
- (void)acceptConnectionInBackgroundAndNotifyForModes:(nullable NSArray<NSRunLoopMode> *)modes;
//单线程,同上
- (void)acceptConnectionInBackgroundAndNotify;


//后台写入数据到文件,完成后通知
- (void)waitForDataInBackgroundAndNotifyForModes:(nullable NSArray<NSRunLoopMode> *)modes;
//单线程,同上
- (void)waitForDataInBackgroundAndNotify;

3、NSFileHandle Demo code

int main(int argc, char * argv[]) {

    //对文件的读写操作使用NSFilehandle
    //获取文件管理器
    NSFileManager *manager0 = [NSFileManager defaultManager];
    //实例化一个字符串
    NSString *fileStr = @"Hello world!";

    //转换为NSData对象
    NSData *fileData = [fileStr dataUsingEncoding:NSUTF8StringEncoding];

    //写入的文件路径
    NSString *filePath1 = @"/Users/tailor/Desktop/File.txt";

    //创建文件
    if(![manager0 fileExistsAtPath:filePath1]) {
        //参数1:文件路径
        //参数2:初始化的内容
        //参数3:附加信息,一般置为nil
        [manager0 createFileAtPath:
         filePath1
                          contents:fileData
                        attributes:nil];
    }

    //只读权限打开
    __unused NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:filePath1];
    //只写权限打开
    __unused NSFileHandle *writeHandle = [NSFileHandle fileHandleForWritingAtPath:filePath1];
    //读写权限打开
    NSFileHandle *updateHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath1];
    //读取文件,从游标(指针)位置(此时在文件起始位置)读到文件末尾
    NSData *readData = [updateHandle readDataToEndOfFile];
    //转化成为字符串
    NSLog(@"%@",[[NSString alloc]initWithData:readData encoding:NSUTF8StringEncoding]);

    //读取一段内容
    //更改游标位置至起始位置
    [updateHandle seekToFileOffset:0];
    NSData *readData1 = [updateHandle readDataOfLength:6];  //读取4个字符
    NSLog(@"%@",[[NSString alloc]initWithData:readData1 encoding:NSUTF8StringEncoding]);

    //移动游标到末尾
    [updateHandle seekToEndOfFile];
    //再写入一段内容
    [updateHandle writeData:fileData];

    //快速把字符串对象写入到本地,控制不了游标,只能全写或全读
    NSString *filePath2 = @"/Users/tailor/Desktop/String.txt";
    NSString *filePath3 = @"/Users/tailor/Desktop/Array.plist";
    NSString *filePath4 = @"/Users/tailor/Desktop/Dictionary.plist";

    //字符串
    NSString *plistStr = @"知行合一";
    //参数1:写入的文件路径
    //参数2:是否保证线程安全
    //参数3:编码格式
    //参数4:错误信息
    [plistStr writeToFile:filePath2
               atomically:YES
                 encoding:NSUTF8StringEncoding
                    error:nil];

    //数组
    NSArray *plistArr = @[@"one",@"two",@"three"];
    [plistArr writeToFile:filePath3 atomically:YES];

    //字典
    NSDictionary *pdic = @{@"one":@"1",@"two":@"2",@"three":@"3"};
    [pdic writeToFile:filePath4 atomically:YES];

    //快速读取本地文件转换成为字符串对象
    NSString *resultStr8 = [[NSString alloc]initWithContentsOfFile:filePath2 encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",resultStr8);
    //快速读取本地文件转换成为数组
    NSLog(@"%@",[[NSArray alloc]initWithContentsOfFile:filePath3]);
    //从本地读取字典
    NSLog(@"%@",[[NSDictionary alloc]initWithContentsOfFile:filePath4]);
}

注:__unused前缀,告诉编译器,如果变量未使用就不参与编译,免除不使用时发出警告。

控制台:


333

桌面:


666

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值