• OC-文件操作


    一.归档NSKeyedArchiver==========================

    1.第一种方式:存储一种数据。=====================

    //归档

            //第一种写法

            //对象--文件

            NSArray* array = [[NSArray alloc]initWithObjects:@"zhang",@"wang",@"li", nil];

            NSString* filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.txt"];

            BOOL success = [NSKeyedArchiver archiveRootObject:array toFile:filePath];

            if (success) {

                NSLog(@"保存成功");

            }

            

            //解归档

            NSArray* arr = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

            NSLog(@"%@",arr);

    2.第二种方式:存储并行数据(存储多种数据)。====================================

    //第二种写法:

            NSArray* array = @[@"one",@"two",@"three"];

            NSDictionary* dic = @{@"key":@"value"};

            NSString* str = @"我是中国人,我爱中国";

            

            //NSData 数据流类

            //用来存储复杂的数据,把复杂的数据转成数据流格式,可以方便进行存储和传输。

            //例如:图片、大文件

            //断点续传,假如图片有20M大,

            //发邮件:添加附件

            NSMutableData* data = [[NSMutableData alloc]init];

            

            //initForWritingWithMutableData 指定要写入的数据流文件

            NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];

            

            //编码数据,参数一:要准备编码的数据;参数二:编码数据的key,key随便写

            [archiver encodeObject:array forKey:@"array"];

            [archiver encodeObject:dic forKey:@"dic"];

            [archiver encodeObject:str forKey:@"str"];

            

            //编码完成

            [archiver finishEncoding];

            

            //指定文件路径

            NSString* filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"file2"];

            

            //写入文件

            [data writeToFile:filePath atomically:YES];

            

            //====================************************************=========================//

           

            

            //先把路径下的文件读入数据流中

            NSMutableData* fileData = [[NSMutableData alloc]initWithContentsOfFile:filePath];

            

            //把数据流文件读入到了 解归档中

            NSKeyedUnarchiver* unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:fileData];

            

            //进行解归档

            NSArray* UnArray = [unArchiver decodeObjectForKey:@"array"];

            NSDictionary* UnDic = [unArchiver decodeObjectForKey:@"dic"];

            NSString* UnStr = [unArchiver decodeObjectForKey:@"str"];

            

            //打印

            NSLog(@"%@ %@ %@ ",UnArray,UnDic,UnStr);

    三.第三种归档方式:对类对象进行归档=======================================

    1.先在类的头文件中实现<NSCoding>协议

    2.在.m中重新编码和解码协议。

    //重新initWithCoder 解码方法

    -(id)initWithCoder:(NSCoder *)aDecoder

    {

        NSLog(@"我是解码方法,我负责解码");

        self = [super init];

        if (self) {

            _name = [aDecoder decodeObjectForKey:@"name"];

            _phone = [aDecoder decodeObjectForKey:@"phone"];

            _address = [aDecoder decodeObjectForKey:@"address"];

        }

        return  self;

    }

    //重新编码方法

    -(void)encodeWithCoder:(NSCoder *)aCoder

    {

        [aCoder encodeObject:_name forKey:@"name"];

        [aCoder encodeObject:_phone forKey:@"phone"];

        [aCoder encodeObject:_address forKey:@"address"];

    }

    //【注】forKey:是字符串;编码方法和解码方法字符串要一致

      

    四.NSFileManager 文件管理类===============================================

    1.文件路径------------------------------------------------------------------------------

    //根路径

            NSString* homePath = NSHomeDirectory();

            NSLog(@"%@",homePath);

            

            //oc中有三个目录是可以操作的。

            /*

             1.Documents//文稿目录

             2.tmp//临时目录:程序退出的时候,临时目录内容可能会被情况

             3.library--->Cache//缓存目录//app目录下

             */

            

            //获取Documents  目录

            //写法一

            NSString* Documents = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

            NSLog(@"Documents :%@",Documents);

            

            //写法二

            NSString* Documents1 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES) objectAtIndex:0];

            NSLog(@"Documents : %@",Documents1);

            

            //获取应用程序的主目录

            NSString* userName = NSUserName();

            NSString* rootPath = NSHomeDirectoryForUser(userName);

            NSLog(@"app root path:%@",rootPath);

            

            //获取cache目录

            NSString* cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];

            NSLog(@"cache :%@",cachePath);

            

            //获取tmp目录

            NSString* tmpPath = NSTemporaryDirectory();

            NSLog(@"tmp:%@",tmpPath);

    2.创建目录和文件------------------------------------------------------------------------------------

    //获取根目录

            NSString* homePath = NSHomeDirectory();

            

            //创建了一个文件管理器

            NSFileManager* fileMgr = [NSFileManager defaultManager];

            

            //拼接出想要创建的文件路径

            NSString* filePath = [NSString stringWithFormat:@"%@/myFolder",homePath];

            

            //创建文件目录

            //第一个参数传入想要创建的文件目录,第二个参数指导是否创建不存在的文件夹,yes代表创建

            BOOL isOk = [fileMgr createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];

            if (isOk) {

                NSLog(@"创建文件目录成功");

            }

            

            NSString* string = @"我爱记歌词";

            //把内容写入到指定路径下的指定文件中

            BOOL isWriteOk = [string writeToFile:[NSString stringWithFormat:@"%@/1.txt",filePath] atomically:YES encoding:NSUTF8StringEncoding error:nil];

            if (isWriteOk) {

                NSLog(@"写入文件成功");

            }

            

            //数组保存

            NSArray* array = @[@"我是一",@"我是三",@"我是周7"];

            BOOL isWriteOK1 = [array writeToFile:[NSString stringWithFormat:@"%@/2.txt",filePath] atomically:YES];

            if (isWriteOK1) {

                NSLog(@"数组写入文件成功");

            }

            

            //字典保存

            NSDictionary* dic = @{@"key":@"value"};

            BOOL isWriteOK2 = [dic writeToFile:[NSString stringWithFormat:@"%@/3.txt",filePath] atomically:YES];

            if (isWriteOK2) {

                NSLog(@"字典写入文件成功");

            }

    3.对文件进行重命名---------------------------------------------------------------------------------------------

    //获取根目录

            NSString* homePath = NSHomeDirectory();

            

            //创建了一个文件管理器

            NSFileManager* fileMgr = [NSFileManager defaultManager];

            

            //拼接出想要创建的文件路径

            NSString* filePath = [NSString stringWithFormat:@"%@/myFolder/1.txt",homePath];

            

            [fileMgr moveItemAtPath:filePath toPath:[NSString stringWithFormat:@"%@/ai.txt",homePath] error:nil];

    4.删除一个文件---------------------------------------------------------------------------------------------

    //声明了一个错误信息的对象

            NSError* error;

            

            //获取根目录

            NSString* homePath = NSHomeDirectory();

            

            //创建了一个文件管理器

            NSFileManager* fileMgr = [NSFileManager defaultManager];

            

            //拼接出想要创建的文件路径

            NSString* filePath = [NSString stringWithFormat:@"%@/myFolder/3.txt",homePath];

            

            //删除文件

            //如果方法执行返回是NO,error会保存错误信息,如果方法执行返回是YES,error = nil

            BOOL isok = [fileMgr removeItemAtPath:filePath error:&error];

            if (isok) {

                NSLog(@"删除文件成功");

            }

            else

            {

                NSLog(@"删除文件失败");

                //打印错误信息

                NSLog(@"%@",error.localizedDescription);

            }

    Δ【扩展】NSError类,是一个错误信息类

    //删除文件

            //如果方法执行返回是NO,error会保存错误信息,如果方法执行返回是YES,error = nil

            BOOL isok = [fileMgr removeItemAtPath:filePath error:&error];

    ∆5.删除目录下的所有文件---------------------------------------------------------------------------------------------

            //获取根目录

            NSString* homePath = NSHomeDirectory();

            

            //创建了一个文件管理器

            NSFileManager* fileMgr = [NSFileManager defaultManager];

            

            //拼接出想要创建的文件路径

    //        NSString* filePath = [NSString stringWithFormat:@"%@/myFolder/3.txt",homePath];

            

            //如果删除的目录中不带具体的文件,则删除的是整个目录

            [fileMgr removeItemAtPath:[NSString stringWithFormat:@"%@/myFolder/",homePath] error:nil];

    6.获取目录下的所有文件---------------------------------------------------------------------------------------------

    //获取根目录

            NSString* homePath = NSHomeDirectory();

            

            //创建了一个文件管理器

            NSFileManager* fileMgr = [NSFileManager defaultManager];

            

            //拼接出想要创建的文件路径

            NSString* filePath = [NSString stringWithFormat:@"%@/myFolder/",homePath];

            

            //获取当前目录下的所有文件,包括隐藏文件

            NSArray* allFile = [fileMgr contentsOfDirectoryAtPath:filePath error:nil];

            NSLog(@"%@",allFile);

            

            //获取当前目录以及子目录的所有文件

            NSArray* subAllFile = [fileMgr subpathsOfDirectoryAtPath:filePath error:nil];

            

    7.文件的属性---------------------------------------------------------------------------------------------

    //获取根目录

            NSString* homePath = NSHomeDirectory();

            

            //创建了一个文件管理器

            NSFileManager* fileMgr = [NSFileManager defaultManager];

            

            //拼接出想要创建的文件路径

            NSString* filePath = [NSString stringWithFormat:@"%@/myFolder/3.txt",homePath];

            

            NSDictionary* fileAttribute = [fileMgr fileAttributesAtPath:filePath traverseLink:YES];

            //获取文件的属性

            NSData* data = [fileAttribute objectForKey:NSFileModificationDate];

            NSLog(@"文件的创建日期:%@",data);

            

            //文件占多少字节

            NSNumber * number = [fileAttribute objectForKey:NSFileSize];

            NSLog(@"文件的大小:%@",number);

  • 相关阅读:
    h5移动开发css
    js 小数相加异常
    h5上滑刷新(分页)
    js中的 !!
    图片懒加载(延迟加载)原理及实现
    作用域内优先级及this指针
    函数的属性、方法和构造函数
    判断是否为严格模式
    匿名函数递归调用自身
    闭包
  • 原文地址:https://www.cnblogs.com/GJ-ios/p/5316533.html
Copyright © 2020-2023  润新知