iOS 缓存文件到沙盒目录的执行文件夹下,并再次读取文件

开发中我们经常要将一些文件缓存到沙盒路径下,并且把指定的类型储存到指定文件夹下,以便于方便管理。

下面是以图片为例

首先显示缓存到指定文件夹下,注释解释很详细


/**

 将图片存储到沙盒目录下存储成jpg形式,可以将图片保存成不通的格式类型、pngjpg ,可自行设置

 

 @param image 图片

 @param imageName 图片名字

 @param extension 后缀,png,jpg

 @param directoryPath 沙盒路径

 @param EcmChatMyPic 沙盒路径下的文件夹

 */

+ (void) saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath{

    NSData *data  = UIImageJPEGRepresentation(image,.000000005);

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *createPath = [NSString stringWithFormat:@"%@/EcmChatMyPic", directoryPath];

    // 判断文件夹是否存在,如果不存在,则创建

    if (![[NSFileManager defaultManager]fileExistsAtPath:createPath]) {

        //如果没有就创建这个 想创建的文件夹   ()

        [fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];

        //然后保存

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

        NSString *imgFileName = [NSString stringWithFormat:@"/%@.%@",imageName,extension];

        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:imgFileName]contents:data attributes:nil];

    } else {

        //文件夹存在   直接保存

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

        NSString *imgFileName = [NSString stringWithFormat:@"/%@.%@",imageName,extension];

        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:imgFileName]contents:data attributes:nil];

    }

}

在下来就是读取了

NSFileManager *fileManager = [NSFileManager defaultManager];    

NSString *document=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

 NSString *folder =[document stringByAppendingPathComponent:@"EcmChatMyPic"];

    

 NSArray *fileList ;

    

    fileList =[fileManager contentsOfDirectoryAtPath:folder error:NULL];

    

    for (NSString *file in fileList) {

        

        NSLog(@"file=%@",file);

        

        NSString *path =[folder stringByAppendingPathComponent:file];

        

        NSLog(@"得到的路径=%@",path);

        

    }


fileList储存的就是所有文件路径的唯一标识,使用的时候就直接使用 path

这样就实现类分类存储


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王 哪跑!!!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值