iOS的文件读写

来源:互联网 发布:音乐喷泉软件下载 编辑:程序博客网 时间:2024/04/29 23:13

应用程序沙盒

苹果公司为iOS每一个应用都分配了一个独立的文件夹,并且将应用程序所能读写的位置几乎都限定在这个文件夹里,这个文件夹可以看做是一个特殊的区域,我们称之为应用程序沙盒(sandbox)。

/*/*IOS文件系统  当第一次启动APP的时候,ios操作系统就为此APP创建一个文件系统,该文件系统下默认有四个目录,分别是:  Document:存储用户在操作APP时产生的数据,此目录下的数据可以通过iCloud进行同步  Library:用户偏好设置,通常和此类NSUserDefaults搭配使用,在此目录下的数据可以通过iCloud进行同步  tmp:存放临时数据,在此目录下的数据不会通过iCloud进行同步  app包:开发者不会操作此目录,通常是通过NSBundle来获取包内资源,如工程素材*/

文件的一些读取操作

获取根目录

NSString *rootPath = NSHomeDirectory();

获取根目录下的 Documents,自动添加‘/’

NSString *documentsPath = [rootPath stringByAppendingPathComponent:@"Documents"];//或者    documentsPath = [rootPath stringByAppendingFormat:@"/Documents"];

最常用的获取Documents目录的方式

documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

下载一个视频文件到Documents目录下的video文件夹

//创建一个方法,用来创建目标文件夹- (NSString *)creatDirInDocuments:(NSString *)dirName{    //获取Documents文件的路径    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];    //拼接成我们想要的文件的路径的字符串    NSString *dirDocuments = [documentsPath stringByAppendingPathComponent:dirName];    //NSFileManager  单例类,用于文件的操作    NSFileManager *fileManager = [NSFileManager defaultManager];    //判断本地是否存在要创建的文件夹    BOOL isExist = [fileManager fileExistsAtPath:dirDocuments];    if (!isExist) {        //创建文件夹        NSError *error;        BOOL isSuccess = [fileManager createDirectoryAtPath:dirDocuments withIntermediateDirectories:YES attributes:nil error:&error];        if (!isSuccess) {            //如果文件夹创建失败,将错误信息打印            NSLog(@"error = %@",error.debugDescription);            dirDocuments = nil;        }    }    return dirDocuments;}

下载视频并存入到指定文件夹

 NSString *video = [self creatDirInDocuments:@"video"];    if (video != nil) {        NSString *videoUrlString = @"http://163.177.2.46/youku/6573B6F49204983389C86C2949/0300080100536FBEDAABC00172D4733C053123-91E7-7011-9F9B-ECC617DC9593.mp4";        NSString *filePath = [video stringByAppendingPathComponent:[videoUrlString lastPathComponent]];        //如果文件夹中不存在该路径        NSFileManager *fileManager = [NSFileManager defaultManager];        if (![fileManager fileExistsAtPath:filePath]) {            //下载视频并存储到data中//            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:videoUrlString]];            //用fileManager的对象,将文件写入本地            BOOL isSuccess = [fileManager createFileAtPath:filePath contents:nil attributes:nil];            if (isSuccess) {                NSLog(@"视频下载成功!");            }            else{                NSLog(@"视频下载失败");            }        }    }

获取Library

NSString *library = [rootPath stringByAppendingPathComponent:@"Library"];    library = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];

下载并保存文件到tmp里面

//创建一个方法- (NSString *)creatDirInTmp:(NSString *)dirName{    NSString *tmpPath = NSTemporaryDirectory();    //创建文件夹路径    NSString *dirPath = [tmpPath stringByAppendingPathComponent:dirName];    NSFileManager *fileManager = [NSFileManager defaultManager];    if (![fileManager fileExistsAtPath:dirPath]) {        NSError *error;        BOOL isSuccess = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error];        if (!isSuccess) {            NSLog(@"error = %@",error.debugDescription);            dirPath = nil;        }    }    return dirPath;}
 //tmp    NSString *tmpString = NSTemporaryDirectory();    NSString *imgsTmpPath = [self creatDirInTmp:@"Imgs"];    NSArray *imgsArray = @[@"http://b.hiphotos.baidu.com/image/pic/item/b8389b504fc2d562acd3bf97e41190ef77c66cf4.jpg",@"http://lady.southcn.com/6/images/attachement/jpg/site4/20160815/35/16085136310361609675.jpg",@"http://e.hiphotos.baidu.com/image/pic/item/d8f9d72a6059252d20b9727e379b033b5bb5b91a.jpg"];    if (imgsTmpPath != nil) {        for (int i = 0; i < imgsArray.count; i++) {            NSString *imgsString = [imgsArray[i] lastPathComponent];            //每一张图片的路径            NSString *imgPath = [imgsTmpPath stringByAppendingPathComponent:imgsString];            //判断是否存在要下载的图片,如果不存在则下载            NSFileManager *fileManager = [NSFileManager defaultManager];            if (![fileManager fileExistsAtPath:imgPath]) {              //将每张图片的url进行编码,有中文等特殊字符时需要                NSString *urlString = [imgsArray[i] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];                if (data  == nil) {                    NSLog(@"网络有问题,请稍后再下载");                }                else{                    BOOL isSuccess = [data writeToFile:imgPath atomically:YES];                    if (isSuccess) {                        NSLog(@"图片下载成功");                    }                    else{                        NSLog(@"图片下载失败");                    }                }            }        }    }

将字符串写入到本地

NSString *targetString = @"经纪人";    BOOL flag = [targetString writeToFile:[imgsTmpPath stringByAppendingPathComponent:@"a.txt"] atomically:YES encoding:NSUTF8StringEncoding error:nil];    if (flag) {        NSLog(@"字符串写入成功");    }    else{        NSLog(@"字符串写入失败");    }

将数组写入本地

NSArray *array1 = @[@"马蓉",@"宝宝",@"aaa"];    BOOL flag1 = [array1 writeToFile:[imgsTmpPath stringByAppendingPathComponent:@"array.txt"] atomically:YES];    if (flag1) {        NSLog(@"数组写入成功");    }    else{        NSLog(@"数组写入失败");    }

将字典写入本地

NSDictionary *dic = @{@"name":@"宝宝",@"age":@24,@"address":@"GZ"};    BOOL flag2 = [dic writeToFile:[imgsTmpPath stringByAppendingPathComponent:@"dic.txt"] atomically:YES];    if (flag2) {        NSLog(@"字典写入成功");    }    else{        NSLog(@"字典写入失败");    }

计算文件大小

NSFileManager *fileManager = [NSFileManager defaultManager];    NSArray *fileManagerArray = [fileManager subpathsAtPath:imgsTmpPath];//    for (int i = 0; i < fileManagerArray.count; i++) {//        //  //    }//    CGFloat count = 0.0;    for (NSString *ele in fileManagerArray) {        NSData *data = [NSData dataWithContentsOfFile:[imgsTmpPath stringByAppendingPathComponent:ele]];        count += data.length;    }    count = count/1024/1024;    NSLog(@"缓存文件的大小为%.2f",count);

删除文件

for (NSString *ele in fileManagerArray) {       BOOL isSuccess = [fileManager removeItemAtPath:[imgsTmpPath stringByAppendingPathComponent:ele] error:nil];        if (isSuccess) {            NSLog(@"删除成功");        }    }

app包,获取包内的图片,显示在UI上

NSBundle *bundle = [NSBundle mainBundle];    NSString *imgPath = [bundle pathForResource:@"b8389b504fc2d562acd3bf97e41190ef77c66cf4" ofType:@".jpg"];    NSData *imgData = [NSData dataWithContentsOfFile:imgPath];    self.picimageview.image = [UIImage imageWithData:imgData];
0 0
原创粉丝点击