我最近在做项目的时候会用到关于沙盒的处理,以下是常用的操作:
1. 文件写入操作
#pragma mark文件写入操作
-(void)writeImageFileToDocument {
//声明一个文件管理器
NSFileManager*manger = [NSFileManagerdefaultManager];
//获取沙盒路径
NSString* writePath = [NSHomeDirectory()stringByAppendingPathComponent:@"/Documents"];
//文件路径
NSString*imagePath=[writePathstringByAppendingPathComponent:@"DSL.jpg"];
if([mangerfileExistsAtPath:imagePath]) {
NSLog(@" image is exist");
return;
}
//将图片写到沙盒中
NSString*sourcePath = [[NSBundlemainBundle]pathForResource:@"1.jpg"ofType:nil];
NSData*iamgeData = [NSDatadataWithContentsOfFile:sourcePath];
if([iamgeDatawriteToFile:imagePathatomically:YES]) {
NSLog(@"write image success");
}
2.文件读取操作
#pragma mark文件读取操作
- (void)readImageFileFromDocument{
//获取路径
NSString* imagePath = [NSHomeDirectory()stringByAppendingPathComponent:@"/Documents/DSL.jpg"];
//显示
self.successImage.image= [UIImageimageWithContentsOfFile:imagePath];
}
3.删除文件操作
#pragma mark删除文件操作
- (void)deleteDocument{
//获取路径
NSString* imagePath = [NSHomeDirectory()stringByAppendingPathComponent:@"/Documents/DSL.jpg"];
NSFileManager*manger = [NSFileManagerdefaultManager];
NSError* error;
[mangerremoveItemAtPath:imagePatherror:&error];
if(error) {
NSLog(@"delete error == %@",[errorlocalizedDescription]);
}else{
NSLog(@" delete success");
}
}
3.在沙盒中新建一个文件夹
#pragma mark在沙盒中新建一个文件夹
- (void)createFilder
{
//沙盒文件的路径
NSString* documentStr = [NSHomeDirectory()stringByAppendingPathComponent:@"/Documents"];
//新的文件的路径
NSString* newFilderPath = [documentStrstringByAppendingPathComponent:@"/DSLFilder"];
NSFileManager* manger = [NSFileManagerdefaultManager];
NSError* error;
//创建操作
[mangercreateDirectoryAtPath:newFilderPathwithIntermediateDirectories:YESattributes:nilerror:&error];
if(error) {
NSLog(@"create filder failed == %@",[errorlocalizedDescription]);
}else{
NSLog(@"create filder success");
}
}
4.给新建的文件写入一个张图片
#pragma mark给新建的文件写入一个张图片
- (void)writeImageToNewFilder{
//新的文件的路径
NSString* documentStr = [NSHomeDirectory()stringByAppendingPathComponent:@"/Documents/DSLFilder/DSL.jpg"];
//将图片写到沙盒中
NSString*sourcePath = [[NSBundlemainBundle]pathForResource:@"1.jpg"ofType:nil];
NSError* error;
[[NSFileManagerdefaultManager]copyItemAtPath:sourcePathtoPath:documentStrerror:&error];
//这里用copy
if(error) {
NSLog(@"write image failed==%@",[errorlocalizedDescription]);
}else{
NSLog(@"write image success");
}
}
5.获取某个目录下的所有文件名
#pragma mark获取某个目录下的所有文件名
- (void)getAllDocumentName{
//获取需要查找的路径
NSString* documentPath = [NSHomeDirectory()stringByAppendingPathComponent:@"/Documents/DSLFilder"];
NSArray* namesArray =nil;
NSError* error;
namesArray = [[NSFileManagerdefaultManager]contentsOfDirectoryAtPath:documentPatherror:&error];
if(error) {
}else
{
[namesArrayenumerateObjectsUsingBlock:^(id_Nonnullobj,NSUIntegeridx,BOOL*_Nonnullstop) {
if([objhasSuffix:@"jpg"]) {
NSLog(@"=====%@",obj);
}
}];
}
}
相关demo 没啦,结束啦