OC中的文件管理

这篇博客详细介绍了iOS应用程序中文件系统的管理,包括Documents、Library和tmp目录的用途。作者展示了如何在Documents目录下创建子目录,检查文件或目录是否存在,创建文件夹,写入和读取文件,以及计算文件大小。虽然没有实现文件删除和移动,但提到了相关API的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
iOS文件系统
当第一次启动app时,iOS操作系统就为此APP创建了一个文件系统,该文件系统下默认有四个目录,分别是:
Documents:存储用户在操作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];
NSLog(@"documentsPath = %@",documentsPath);

//下载一个视频文件到Document目录下的Video文件夹下
/*

NSString *videoDir = [self createDirInDocuments:@”videos”];
if (videoDir != nil) {
NSFileManager *fm = [NSFileManager defaultManager];

    NSString *videoUrlString = @"http://v8.tv.cctv5.cctv.com/r5wbth/4d/e7/4de76971-63f4-4717-f28b-03d757a7704f/mp4h.mp4";

    NSString *fileVideo = [videoDir stringByAppendingPathComponent:[videoUrlString lastPathComponent]];

    if (![fm fileExistsAtPath:fileVideo]) {
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:videoUrlString]];
        BOOL isSuccess = [fm createFileAtPath:fileVideo contents:data attributes:nil];
        if (!isSuccess) {
            //如果写入不成功,则提示信息
            NSLog(@"视频下载不成功");
        }else{
            NSLog(@"视频下载成功");
        }

    }



}
*/



//字符串拼接,获取Library目录
NSString *libraryPath = [rootPath stringByAppendingString:@"Library"];
//C函数获取Library目录
libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];

//tmp
NSString *tmpPath = NSTemporaryDirectory();
//下载一些图片放到tmp目录下的Imgs文件夹下,如果有些图片已经下载,那么不会继续下载

//创建文件夹
//获取NSFileManager单例类,用于文件操作
NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *imgsDirectory = [tmpPath stringByAppendingPathComponent:@"Imgs"];

//来判断本地是否存在某个文件或者文件夹

BOOL isExist = [fileManager fileExistsAtPath:imgsDirectory];
NSError *error;
if (!isExist) {
//创建文件夹
BOOL isSuccess = [fileManager createDirectoryAtPath:imgsDirectory withIntermediateDirectories:YES attributes:nil error:&error];
if (!isSuccess) {
//如果文件创建失败,将打印错误信息
NSLog(@”error = %@”,error.debugDescription);
}
}

NSArray *imgsArray = @[@"http://s0.hao123img.com/res/r/image/2015-08-11/cc1eb723b3afec8d1f65d1edbe794349.jpg",@"http://s0.hao123img.com/res/r/image/2015-08-11/867fdb3ab71b3a31b2c2a763ca84d8ea.jpg",@"http://s0.hao123img.com/res/r/image/2015-08-11/2bf0ad9342cd778452b6e432fc36626d.jpg",@"http://s0.hao123img.com/res/r/image/2015-08-11/608a6bde897e66560752247706452dce.jpg"];

for (int i = 0; i < imgsArray.count; i++) {
    //获取图片路径
    NSString *imgPath = [imgsArray[i] lastPathComponent];
    imgPath = [imgsDirectory stringByAppendingPathComponent:imgPath];


    //如果图片已经下载,将不会下载图片
    if (![fileManager fileExistsAtPath:imgPath]) {
        //将url进行编码
        NSString *urlString = [imgsArray[i] stringByAddingPercentEscapesUsingEncoding:4];
        //将urlString转换成NSURL,将NSURL转换成NSData
        NSURL *url = [NSURL URLWithString:urlString];
        NSData *data = [NSData dataWithContentsOfURL:url];
        if (data == nil) {
            NSLog(@"网络有问题!");
        }else{
            //将转换成的data写入本地Imgs文件夹
            BOOL isSuccess = [fileManager createFileAtPath:imgPath contents:data attributes:nil];
            if (!isSuccess) {
                //如果写入不成功,则提示信息
                NSLog(@"图片写入不成功");
            }else{
                NSLog(@"图片下载成功");
            }
        }


    }else{
        NSLog(@"图片已经下载");
    }


}

//将字符串写入到本地
NSString *targetString = @"vincent is very very handsome man,he always say:我为何如此屌";
BOOL flag =  [targetString writeToFile:[imgsDirectory stringByAppendingPathComponent:@"des.txt"] atomically:YES encoding:4 error:nil];
if (flag) {
    NSLog(@"写入成功");
}else{
    NSLog(@"写入失败");
}

NSArray *array = @[@"常龙",@"李书城",@"性蒸鱼",@"颜树辛",@"罗全爽",@"刘家豪",@"张远套",@"郭明见",@"盘致敬",@"方剑青",[Student new]];

flag = [array writeToFile:[imgsDirectory stringByAppendingPathComponent:@”array.txt”] atomically:YES];
if (flag) {
NSLog(@”写入成功”);
}else{
NSLog(@”写入失败”);
}

NSDictionary *dic = @{@"name":@"vincent"};
flag = [dic writeToFile:[imgsDirectory stringByAppendingPathComponent:@"dic.txt"] atomically:YES];
if (flag) {
    NSLog(@"写入成功");
}else{
    NSLog(@"写入失败");
}

//计算文件大小
//获得将要计算的文件夹

NSArray *imgsFileArray = [fileManager subpathsAtPath:imgsDirectory];//API
CGFloat count = 0.0;
for (NSString *ele in imgsFileArray) {
NSData *data = [NSData dataWithContentsOfFile:[imgsDirectory stringByAppendingPathComponent:ele]];
count += data.length;
}
count = count/1024/1024;

NSLog(@"缓存文件的大小为%.2fM",count);

//删除文件

// for (NSString *ele in imgsFileArray) {
// BOOL isSuccess = [fileManager removeItemAtPath: [imgsDirectory stringByAppendingPathComponent:ele] error:&error];
// if (isSuccess) {
// NSLog(@”删除成功”);
// }else{
// NSLog(@”删除失败”);
// }
// }

//app包,获取包内的图片,显示在UI上
NSBundle *bundle = [NSBundle mainBundle];
NSLog(@"bundlePath = %@",bundle.bundlePath);
NSString *imgPath = [bundle pathForResource:@"E7979726-68D5-4A2B-A1BB-E2C5D8C2D65F" ofType:@"png"];
NSData *imgData = [NSData dataWithContentsOfFile:imgPath];
UIImage *image = [UIImage imageWithData:imgData];
self.imageView.image = image;

//移动 复制

// [fileManager moveItemAtPath:<#(NSString )#> toPath:<#(NSString )#> error:<#(NSError __autoreleasing )#>]
// [fileManager copyItemAtPath:<#(NSString )#> toPath:<#(NSString )#> error:<#(NSError __autoreleasing )#>]

}

-(NSString )createDirInDocuments:(NSString )dirName{
NSString * documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//获取NSFileManager单例类,用于文件操作
NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *imgsDirectory = [documentsPath stringByAppendingPathComponent:dirName];

//来判断本地是否存在某个文件或者文件夹
BOOL isExist = [fileManager fileExistsAtPath:imgsDirectory];
NSError *error;
if (!isExist) {
    //创建文件夹
    BOOL isSuccess = [fileManager createDirectoryAtPath:imgsDirectory withIntermediateDirectories:YES attributes:nil error:&error];
    if (!isSuccess) {
        //如果文件创建失败,将打印错误信息
        NSLog(@"error = %@",error.debugDescription);
        imgsDirectory = nil;
    }
}

return imgsDirectory;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值