Mac-NSFileManager使用

给NSString添加分类,判断路径是否存在

///判断路径文件是否存在
- (BOOL)isExistAtPath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isExist = [fileManager fileExistsAtPath:self];
    return isExist;
}

给NSFileManager添加分类,实现删除文件,创建文件,读取文件.

///删除指定路径下的文件
-(void)removeDirectory:(NSString *)path{    
    if ([path isExistAtPath]){
        [[NSFileManager defaultManager]removeItemAtPath:path error:nil];
    }else{
        NSLog(@".sketchImage不存在,不用删除");
    }
}
///指定一个路径 创建一个新的文件夹
-(NSString *)createDirectory:(NSString *)path{
    NSFileManager *fileManager = [NSFileManager defaultManager];    
    if ([path isExistAtPath]){
        NSLog(@"not create");
        return path;
    }else{
        BOOL isSuccess = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
        if (isSuccess) {
            NSLog(@"success");
            return path;
        } else {
            NSLog(@"fail");
            return nil;
        }
    }
    return nil;
}
///获取路径下所有文件
-(NSArray*)fetchDirectory:(NSString*)path {    
    NSMutableArray* array = [NSMutableArray array];
    if ([path isExistAtPath]){
        NSFileManager* fileMgr = [NSFileManager defaultManager];
        NSArray* tempArray = [fileMgr contentsOfDirectoryAtPath:path error:nil];
        for (NSString* fileName in tempArray) {
            BOOL flag = YES;
            NSString* fullPath = [path stringByAppendingPathComponent:fileName];
            if ([fileMgr fileExistsAtPath:fullPath isDirectory:&flag]) {
                if (!flag) {
                    [array addObject:fullPath];
                }
            }
        }
        return array;
    }
    
    NSLog(@"没有找到路径,无法读取");
    
    return array;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 大纲 26.Protocol-协议 27.delegate-代理 28.Foundation框架介绍 29.NSS...
    天天想念阅读 1,390评论 0 2
  • 27、ViewController的didReceiveMemoryWarning是在什么时候调用的?默认的操作是...
    烟雨平生花飞舞阅读 647评论 0 1
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,275评论 30 472
  • 下面是我最近两年学习OC中的一些基础知识,对于学习OC基础知识的人可能有些帮助,拿出来分享一下,还是那句话不喜勿喷...
    小小赵纸农阅读 2,699评论 1 7
  • 218.241.181.202 wxhl60 123456 192.168.10.253 wxhl66 wxhl6...
    CYC666阅读 1,489评论 0 6