文件管理器与文件对接器以及复杂对象的读写(I/O)操作

SendBoxPaths是我自己写的简单对象读写(I/O)操作的封装方法

*以下关于这类[SendBoxPaths ...Path]的是我调用自己封装的方法 有兴趣的朋友可以看看
http://www.jianshu.com/p/12f2cb693b67


文件管理器(NSFileManager)

  • 此类主要是对文件进行的操作(创建/删除/改名等)以及文件信息的获取。
  • 以下是NSFileManager的一些操作方法


    44CC2734-2923-4A31-A291-D8AF9F4F8A9C.png
44CC2734-2923-4A31-A291-D8AF9F4F8A9C.png

记得导包 #import "SendBoxPaths.h"

//NSFileManager的应用
- (void)myFileManager{
    //获取文件管理对象
    NSFileManager* fileManager = [NSFileManager defaultManager];
    //创建文件,并写入数据,如果该方法的返回值为YES:文件创建成功或者文件已经存在,
    //第一个参数:要创建文件的路径
    //第二个参数:要创建文件的内容
    //第三个参数:要设置文件的用户组、权限、修改时间等设置。如果赋值为nil,系统会为文件加一些默认设置
    //创建文件路径
    NSString* path = [[SendBoxPaths cachesPath] stringByAppendingPathComponent:@"array.json"];
    //创建要写入的内容
    NSArray* array = @[@"王",@"余",@"李",@"雷"];
    //数组转为NSData
    NSData* arrayData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
    BOOL isSuccess = [fileManager createFileAtPath:path contents:arrayData attributes:nil];
    if (isSuccess) {
        NSLog(@"isSuccess---%@",[SendBoxPaths cachesPath]);
    }else{
        NSLog(@"fail");
    }
    //读取数据
    //先判断该路径下文件是否存在
    if ([fileManager fileExistsAtPath:path]) {
    
    NSData* readData = [fileManager contentsAtPath:path];
    NSArray* readArray = [NSJSONSerialization JSONObjectWithData:readData options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"readArray---%@",readArray);
    }else{
        NSLog(@"该路径下文件不存在");
    }
    
//    
//    //将caches中的文件的array.json文件移动到documents下
//    BOOL isMove = [fileManager moveItemAtPath:path toPath:[[SendBoxPaths documentsPath] stringByAppendingPathComponent:@"newArray.json"] error:nil];
//    if (isMove) {
//        NSLog(@"移动成功");
//    }else{
//        NSLog(@"移动失败");
//    }
    NSLog(@"documentsPath--%@",[SendBoxPaths documentsPath]);
    //将原有路径下的文件cory到新的路径下
    BOOL isCopy = [fileManager copyItemAtPath:path toPath:[[SendBoxPaths documentsPath] stringByAppendingPathComponent:@"copyArray.json" ] error:nil];
    if (isCopy) {
         NSLog(@"coyp成功");
    }else{
        NSLog(@"coyp失败");
    }
    //比较文件内容
    BOOL isEqual = [fileManager contentsEqualAtPath:path andPath:[[SendBoxPaths documentsPath] stringByAppendingPathComponent:@"copyArray.json" ]];
    if (isEqual) {
        NSLog(@"文件内容相同");
    }else{
        NSLog(@"文件内容不同");
    }
    
    //删除文件
    BOOL isRemove = [fileManager removeItemAtPath:path error:nil];
    if (isRemove) {
        NSLog(@"删除成功");
    }else{
        NSLog(@"删除失败");
    }
    //创建文件夹
    //第一个参数:要创建的文件夹的路径
    //第二个参数:YES:如果父目录(文件夹)不存在,创建的时候会将父目录一起创建;NO:如果父类目录不存在,那么文件夹就会创建失败
    //第三个参数:文件夹的权限
    BOOL iscreate = [fileManager createDirectoryAtPath:[[SendBoxPaths homePath] stringByAppendingPathComponent:@"AAA/bbb" ]  withIntermediateDirectories:YES attributes:nil error:nil];
    if (iscreate) {
        NSLog(@"创建成功");
    }else{
        NSLog(@"创建失败");
    }
    NSLog(@"homePath---%@",[SendBoxPaths homePath]);
}
  • 切记要在- (void)viewDidLoad;方法里面调用

文件连接器(NSFileHandle)

  • 是非常基础的只针对“文件内容”的操作(读取、写入和更新)。
  • 使用场景 对文件内容的进行局部修改、追加内容。
  • 使用步骤
    1.文件对接并获取一个NSFilehandle对象
    2.读写操作
    3.关闭对接
  • *注意
    NSFileHandle类并没有提供创建文件的功能。必须使用NSFileManager方法来创建文件。因此在使用下面表中的方法是,都是保证文件以及存放在,否则返回nil.
  • 文件对接器(NSFileHandle)的 一些方法
A7896233-2F8D-403A-B9D9-CC34EE11CD45.png
752D79E4-5404-41B8-A748-CF815796E1B4.png

记得导#import "SendBoxPaths.h" 包

//NSFileHandle的使用
-(void)myFileHandle{
    //判断某个路径下的文件是否存在,如果存在直接通过handle对象向里面写入内容;如果不存在,先创建该文件,在进行操作。
    //获取文件管理对象
    NSFileManager* fileManager = [NSFileManager defaultManager];
    NSString* path = [[SendBoxPaths documentsPath] stringByAppendingPathComponent:@"test.txt"];
    BOOL isExists = [fileManager fileExistsAtPath:path];
    if (!isExists) {
        //文件不存在  创建
        [fileManager createFileAtPath:path contents:nil attributes:nil];
    }
    //对文件内容进行操作
    //向文件写入内容
    NSFileHandle* fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
    //准备数据
    NSString* inputString = @"111111";
    NSData* inputData = [inputString dataUsingEncoding:NSUTF8StringEncoding];
    //写入
    [fileHandle writeData:inputData];
    //操作完毕,一定要关闭
    [fileHandle closeFile];
    //更新数据为 刘·最帅·元
    NSFileHandle* updateFileHandle = [NSFileHandle fileHandleForUpdatingAtPath:path];
    //我们要从“刘”之后写入数据,我们需要将文件偏移量设置为1,然后再开始写入。 相当于从1位置开始,将后面的内容进行替换
    [updateFileHandle seekToFileOffset:1];
    //写入要增加的数据
    NSData* addData = [@"23" dataUsingEncoding:NSUTF8StringEncoding];
    [updateFileHandle writeData:addData];
    //操作完毕,一定要关闭
    [updateFileHandle closeFile];
    //读取
    NSFileHandle* readFileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
    //设置要读取的多长内容
//    NSData* readData = [readFileHandle readDataOfLength:3];
    NSData* readData = [readFileHandle readDataToEndOfFile];//读取所有的内容
    //关闭
    [readFileHandle closeFile];
    //将data转换为字符串
    NSString*  readSting = [[NSString alloc] initWithData:readData encoding:NSUTF8StringEncoding];
    NSLog(@"readSting---%@",readSting);
}
  • 切记要在- (void)viewDidLoad;方法里面调用

复杂对象的读写(I/O)操作

复杂对象

  • 在Foundation框架内 不存在的数据类, 如:自定义Person类 无法再程序内通过writeToFile:这个方法写入到文件内

归档与反归档

  • 如何将复杂对象写入文件?
    复杂对象无法通过writeToFile:方法进行数据持久化,只能通过将复杂对象转为nSData(这个步骤就是归档),然后在通过writeToFile:写入文件
  • 记住
    1.复杂对象写入文件的过程(复杂对象 ->归档->NSData->writeToFile:)
    2.从文件读取复杂对象过程(读取文件->NSData->反归档->复杂对象)
  • 复杂对象所属的类要遵守<NSCoding>协议
  • 实现协议中的两个方法
    1.-(void)encodeWithCoder:(NSCoder *)aCoder;
    2.-(id)initWithCoder:(NSCoder *)aDecoder;

代码示例

首先建一个Person类

#import <Foundation/Foundation.h>
//要对复杂对象进行归档,必须遵循一个协议
@interface Person : NSObject<NSCoding>
@property (nonatomic,strong) NSString* name;
@property (nonatomic,assign) int age;
@end
#Person的.m
#import "Person.h"
@implementation Person
//归档的过程:相当于将复杂对象转NSData类型,为了写入文件。
-(void)encodeWithCoder:(NSCoder *)aCoder{
    //归档的过程是将当前对象每一个属性都进行编码。
    //第一个参数:要进行编码的属性的值
    //第二个参数:为属性的值加标记,加标记是为了解码使用
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInt:self.age forKey:@"age"];
    NSLog(@"调用归档的方法");
}
//反归档:将NSData转换为复杂对象,为了读取使用。
-(id)initWithCoder:(NSCoder *)aDecoder{
    NSLog(@"调用反归档的方法");
    self = [super init];
    if (self) {
        //解码 从文件中读取出来值,赋值给对应的属性
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [aDecoder decodeIntForKey:@"age"];
    }
    return self;
}
@end

在ViewController.m中记得导包

#import "SendBoxPaths.h"

#import "Person.h"

*代码示例

//归档的过程
- (void)myEncoder{
    //需要声明创建一个person对象用来归档
    Person* person = [[Person alloc] init];
    person.name = @"刘元";
    person.age = 123;
    //需要创建一个可变的data对象,用来存放归档好的person对象
    NSMutableData* mData = [[NSMutableData alloc]init];
    //创建归档工具对象
    //参数为要承接归档完成的复杂对象:
    NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:mData];
    //归档
    //第一个参数:要归档的复杂对象
    //第二个参数:标记,为了反归档使用
    [archiver encodeObject:person forKey:@"person"];
    //归档结束,一定调用下面这个方法,要不然mData中不会有值
    [archiver finishEncoding];
    //将MData持久化到本地文件
    NSString* path = [[SendBoxPaths documentsPath]stringByAppendingPathComponent:@"archiver.data"];
    [mData writeToFile:path atomically:YES];
}
//反归档
-(void)unArchiver{
    //将刚才归档文件中的data数据读取出来,以便反归档使用
    NSString* path = [[SendBoxPaths documentsPath]stringByAppendingPathComponent:@"archiver.data"];
    NSData* data = [NSData dataWithContentsOfFile:path];
    //初始化一个反归档工具
    NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    //反归档
    Person* person = [unarchiver decodeObjectForKey:@"person"];
    //反归档结束的方法,必须调用
    [unarchiver finishDecoding];
    NSLog(@"name === %@,age === %d",person.name,person.age);
}
  • 切记要在- (void)viewDidLoad;方法里面调用

不足之处希望大家见谅,我会在更新

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本章包含的四个知识点: 一、沙盒机制 二、简单对象的写入与读取 三、文件管理器 四、复杂对象的写入与读取 一、 i...
    逗逗豆豆笑阅读 1,463评论 0 5
  • 下面是我最近两年学习OC中的一些基础知识,对于学习OC基础知识的人可能有些帮助,拿出来分享一下,还是那句话不喜勿喷...
    小小赵纸农阅读 2,662评论 1 7
  • 一、数据持久化概述 数据持久化就是数据的永久存储。其本质是将数据保存为文件,存到程序的沙盒中。 1、数据持久化的方...
    lilinjianshu阅读 644评论 0 1
  • iOS 開発の結構 画面 UI UIWebview [[UIApplication sharedApplicati...
    RencaiXiong阅读 606评论 0 0
  • 本文结构 参考孟岩老师的文章,对本文结构如下划分 基本数据类型基本语法数组和其他集合类基本输入输出和文件处理,输入...
    不抄完整本三国不改名阅读 539评论 0 1