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



作者:elite_kai
链接:https://www.jianshu.com/p/b41bf51732fc
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted @ 2021-10-22 12:06  brave-sailor  阅读(214)  评论(0编辑  收藏  举报