ios开发,NSFileManager的使用

由于本人提交app的时候需要修改文件夹的名字,并且给 .m 文件增加函数名称,之前一直是手动操作,每次提交app的时候都要更改,单纯的手动操作就显得太low了,貌似现在脚本写出来的功能都很强大,可惜我不会,所以只好用NSFileManager代替。

在网上我们可以看到很多介绍NSFileManager的文章,接下来我们引用
http://www.jianshu.com/p/64b673ba551b 这篇博客中的知识,学习NSFileManager的基本功能。

- (NSString *)getDocumentsPath
{
    //获取Documents路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSLog(@"path:%@", path);
    return path;
}

创建文件夹

-(void)createDirectory{
    NSString *documentsPath =[self getDocumentsPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *iOSDirectory = [documentsPath stringByAppendingPathComponent:@"iOS"];
    BOOL isSuccess = [fileManager createDirectoryAtPath:iOSDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    if (isSuccess) {
        NSLog(@"success");
    } else {
        NSLog(@"fail");
    }
}

创建文件

-(void)createFile{
    NSString *documentsPath =[self getDocumentsPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *iOSPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    BOOL isSuccess = [fileManager createFileAtPath:iOSPath contents:nil attributes:nil];
    if (isSuccess) {
        NSLog(@"success");
    } else {
        NSLog(@"fail");
    }
}

写文件

-(void)writeFile{
    NSString *documentsPath =[self getDocumentsPath];
    NSString *iOSPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    NSString *content = @"我要写数据啦";
    BOOL isSuccess = [content writeToFile:iOSPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if (isSuccess) {
        NSLog(@"write success");
    } else {
        NSLog(@"write fail");
    }
}

读取文件内容

-(void)readFileContent{
    NSString *documentsPath =[self getDocumentsPath];
    NSString *iOSPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    NSString *content = [NSString stringWithContentsOfFile:iOSPath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"read success: %@",content);
}

判断文件是否存在

- (BOOL)isSxistAtPath:(NSString *)filePath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isExist = [fileManager fileExistsAtPath:filePath];
    return isExist;
}

计算文件大小

- (unsigned long long)fileSizeAtPath:(NSString *)filePath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isExist = [fileManager fileExistsAtPath:filePath];
    if (isExist){
        unsigned long long fileSize = [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
        return fileSize;
    } else {
        NSLog(@"file is not exist");
        return 0;
    }
}

计算整个文件夹中所有文件大小

- (unsigned long long)folderSizeAtPath:(NSString*)folderPath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isExist = [fileManager fileExistsAtPath:folderPath];
    if (isExist){
        NSEnumerator *childFileEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator];
        unsigned long long folderSize = 0;
        NSString *fileName = @"";
        while ((fileName = [childFileEnumerator nextObject]) != nil){
            NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
            folderSize += [self fileSizeAtPath:fileAbsolutePath];
        }
        return folderSize / (1024.0 * 1024.0);
    } else {
        NSLog(@"file is not exist");
        return 0;
    }
}

删除文件

-(void)deleteFile{
    NSString *documentsPath =[self getDocumentsPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *iOSPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    BOOL isSuccess = [fileManager removeItemAtPath:iOSPath error:nil];
    if (isSuccess) {
        NSLog(@"delete success");
    }else{
        NSLog(@"delete fail");
    }
}

移动文件

- (void)moveFileName
{
    NSString *documentsPath =[self getDocumentsPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    NSString *moveToPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    BOOL isSuccess = [fileManager moveItemAtPath:filePath toPath:moveToPath error:nil];
    if (isSuccess) {
        NSLog(@"rename success");
    }else{
        NSLog(@"rename fail");
    }
}

重命名

- (void)renameFileName
{
    //通过移动该文件对文件重命名
    NSString *documentsPath =[self getDocumentsPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    NSString *moveToPath = [documentsPath stringByAppendingPathComponent:@"rename.txt"];
    BOOL isSuccess = [fileManager moveItemAtPath:filePath toPath:moveToPath error:nil];
    if (isSuccess) {
        NSLog(@"rename success");
    }else{
        NSLog(@"rename fail");
    }
}

以上内容属于作者李刚

下面我们介绍如何对项目进行操作。

1.利用NSFileManager的最进本的用法操作另外一个项目,同时修改所有.m文件的内容
2.同时修改多个文件夹的名称

直接上代码,里面注释很清楚

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
}

//给所有的.m增加方法
- (IBAction)changeMClass:(id)sender {
    
    //这里面的方法可以自己定义,如果有第三方代码的话,也会添加进去,这没有做判断
    //只需要点击一次就可以了,如果多次点击,会产生重复的代码
    NSArray *array = @[@"- (NSMutableString *)viewWillString:(UIView *)vc withBtn:(NSMutableString *)btnstring{return btnstring;}",
                       @"- (UIBarButtonItem *)viewfromViewController:(NSString *)string withUrl:(NSURL *)url withBtn:(UIBarButtonItem *)btn{return btn;}",
                       @"+ (NSArray *)arrayChangeToString:(NSArray *)string{return string;}",
                       @"+ (UIImage *)stringToDic:(NSDictionary *)dic withArray:(UIImage *)array{return array;}",
                       @"+ (UIColor *)dicFromArray:(NSArray *)array withString:(UIColor *)string{return string;}"
                       ];
    
    NSMutableString *methodString = [NSMutableString string];
    for (NSString *method in array) {
        [methodString appendString:[NSString stringWithFormat:@"%@\n", method]];
    }
    
    NSString *method = [NSString stringWithFormat:@"%@@end", methodString];
    NSLog(@"method---------- %@", method);
    
    NSString *homePath = @"<#项目的地址,直接把项目拖进来#>";
    [self changeMFile:homePath withMethodName:method];
}

//修改文件夹的名字
- (IBAction)changeFileName:(id)sender {
    
    //注意、修改文件夹名字的时候并没有与类的名字或者其他文件的名字做区分,所以这个地方大家要注意
    //如果图片名字也有LXK这个三个字母的话,那么也会一起修改了
    
    NSString *homePath = @"<#项目的地址,直接把项目拖进来#>";
    
    //比如TestProduct这个项目中的名字是LXK,然后这个地方就用LXK
    NSString *lastPath = @"<#项目中文件夹刚开始的名字,命名要统一#>";
    
    //修改后的名字,可以随便写,比如 LRGJ
    NSString *nowPath = @"<#修改后显示出来的文件夹的名字#>";
    
    //这里 “LXK” 开头的文件目录有几层就需要点击几下按钮,
    //比如目录结构 LXKMine->LXKVM->LXKImage->LXKLunch,就需要点击四下,所有的目录中,按照目录层级最多的那个次数点击
    //比如 LXKClass->LXKVM->LXKImage只有三层,所以按照LXKMine->LXKVM->LXKImage->LXKLunch的目录次数点击
    [self listFileAtPath:homePath withPath:lastPath withToPath:nowPath];
    
}


- (void)listFileAtPath:(NSString *)pathName withPath:(NSString *)lastPath withToPath:(NSString *)nowPath{
    
    NSArray *contentOfFolder = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathName error:NULL];
    for (NSString *aPath in contentOfFolder)
    {
        
        NSString *suffix = [aPath pathExtension];
        
        if (!([suffix isEqual:@"m"] || [suffix isEqual:@"h"]))
        {
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSString * fullPath = [pathName stringByAppendingPathComponent:aPath];
            NSMutableString *path = [NSMutableString stringWithFormat:@"%@", fullPath];
            NSString *toPath = [path stringByReplacingOccurrencesOfString:lastPath withString:nowPath];
            [fileManager moveItemAtPath:path toPath:toPath error:NULL];
            
            BOOL isDir;
            if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:&isDir] && isDir)
            {
                [self listFileAtPath:fullPath withPath:lastPath withToPath:nowPath];
            }
        }
    }
}


- (void)changeMFile:(NSString *)pathName withMethodName:(NSString *)methodName
{
    NSMutableArray *fileArray = [NSMutableArray array];
    
    NSArray *contentOfFolder = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathName error:NULL];
    for (NSString *aPath in contentOfFolder) {
        
        NSString * fullPath = [pathName stringByAppendingPathComponent:aPath];
        NSMutableString *path = [NSMutableString stringWithFormat:@"%@", fullPath];
        [fileArray addObject:path];
        
        //从路径中获得完整的文件名 (带后缀)
        //            NSString *fileName = [path lastPathComponent];
        //            NSLog(@"fileName ********************* %@", fileName);
        //            //获得文件的后缀名 (不带'.')
        //            NSString *suffix = [path pathExtension];
        //            NSLog(@"suffix------- %@", suffix);
        
        BOOL isDir;
        if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) {
            [self changeMFile:fullPath withMethodName:methodName];
        }
    }
    
    
    for (NSString *aPath in fileArray)
    {
        NSString *suffix = [aPath pathExtension];
        if ([suffix isEqualToString:@"m"])
        {
            NSString *content=[NSString stringWithContentsOfFile:aPath encoding:NSUTF8StringEncoding error:nil];
            
            NSMutableString *contentString = [NSMutableString stringWithFormat:@"%@", content];
            
            NSArray *endArray = [self rangeOfSubString:@"@end" inString:contentString];
            if (endArray.count > 0)
            {
                
                NSString *rangeString = endArray[endArray.count-1];
                NSRange range = NSRangeFromString(rangeString);
                NSString *noEndString = [contentString stringByReplacingCharactersInRange:range withString:@""];
                NSMutableString *endString = [NSMutableString stringWithFormat:@"%@", noEndString];
                NSString *string = [endString stringByAppendingString:methodName];
                
                BOOL res=[string writeToFile:aPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
                
                if (res) {
                    
                    NSLog(@"文件写入成功");
                    
                }else
                    
                    NSLog(@"文件写入失败");
                
            }
            
        }
    }
    
}


- (NSArray *)rangeOfSubString:(NSString *)subStr inString:(NSString *)string {
    
    NSMutableArray *rangeArray = [NSMutableArray array];
    
    NSString *string1 = [string stringByAppendingString:subStr];
    
    NSString *temp;
    
    for (int i = 0; i < string.length; i ++) {
        
        temp = [string1 substringWithRange:NSMakeRange(i, subStr.length)];
        
        if ([temp isEqualToString:subStr]) {
            
            NSRange range = {i,subStr.length};
            
            [rangeArray addObject:NSStringFromRange(range)];
            
        }
        
    }
    
    return rangeArray;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

下面是代码,大家可以下载尝试一下
https://github.com/elite-kai/ELFileManager

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容

  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,036评论 29 470
  • 218.241.181.202 wxhl60 123456 192.168.10.253 wxhl66 wxhl6...
    CYC666阅读 1,286评论 0 5
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • 你是不是背负着压力 像背着一座山一般 你时常不堪重负,步履艰难 却 不舍得卸下一树一石 有人说 放弃一些吧,别失了...
    赵小羊一阅读 249评论 2 0
  • 生活中有太多美好的景色,值得让我们流连忘返,今年春季的一天,和家人孩子去了厦门,傍晚在海边看到艳丽的晚霞,像是打翻...
    NANA0阅读 261评论 0 0