iOS沙盒大文件存储案例

【重】沙盒大文件存储案例(文件夹路劲可以设置成全局的)

一、创建文件夹和文件

  //(1)创建文件夹,并创建文件
        //用来存放缓存文件,iTunes不会备份此目录,此目录下的文件不会在程序退出后删除,一般存放体积比较大但又不太重要的文件。
        NSString * documentsPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
        NSFileManager *fileManager  = [NSFileManager defaultManager];//初始化一个文件
        
        //创建文件夹
        NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"wenjianjiaName"];
        BOOL res1 =[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
        if (res1) {
            NSLog(@"文件夹创建成功");
        }else{
            NSLog(@"文件夹创建失败");
        }

        //在文件夹下创建文件
        NSString *testPath  = [testDirectory stringByAppendingPathComponent:@"wenjianjiaName.chaoxi"];
        BOOL res2 =[fileManager createFileAtPath:testPath contents:nil attributes:nil];
        if (res2) {
            NSLog(@"文件创建成功: %@" ,testPath);
        }else{
            NSLog(@"文件创建失败");
        }

二、写入文件

  //(2)写入文件(以保存照片为例子)
        NSData* imageData = UIImagePNGRepresentation([UIImage imageNamed:@"默认头像"]);
        BOOL res3 = [imageData writeToFile:testPath atomically:NO];
        if (res3) {
            NSLog(@"文件写入成功");
        }else{
            NSLog(@"文件写入失败");
        }

三、读取文件

   //(3)读取文件(读取图片时用这个路径)
        UIImage * image = [[UIImage alloc]initWithContentsOfFile:testPath];
        //获取文件夹下的所有文件名
        NSArray *arrayFiles = [[NSFileManager defaultManager] subpathsAtPath:testDirectory];

四、删除文件夹或者文件

  //(4)删除文件夹或者文件
        NSString * documentsPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
        //文件夹
        NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"wenjianjiaName"];
        //文件路径
        NSString *testPath  = [testDirectory stringByAppendingPathComponent:@"wenjianjiaName.chaoxi"];
        
        //删除文件夹,删除文件换成testPath路径就可以
        BOOL res =[[NSFileManager defaultManager] removeItemAtPath:testDirectory error:nil];
        if (res) {
            NSLog(@"文件夹删除成功");
        }else{
            NSLog(@"文件夹删除失败");
        }
        
        //附加
        NSLog(@"文件是否存在: %@",[[NSFileManager defaultManager] isExecutableFileAtPath:testPath]?@"YES":@"NO");
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、 沙盒概念基本介绍 iOS 应用程序只能在该 app 的文件系统中读取。这个默认的 app 文件系统就是我们说...
    Laughingg阅读 7,741评论 2 10
  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,795评论 8 265
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,292评论 19 139
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,291评论 30 472
  • 放下之后 卦起的也吉 或许真是有些冥冥中的神秘力量吧 想想看 似乎每次喜欢上一个人之后自己总是操之过急 不懂得徐徐...
    吴阿狸阅读 3,325评论 0 0