数据持久化---文件操作相关方法

//获取应用程序路径

+ (NSString *)getApplicationPath {
    return NSHomeDirectory();
}

//获取Document路径

+ (NSString *)getDocumentPath {
    NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [filePaths objectAtIndex:0];
}

//获取Library路径

+ (NSString *)getLibraryPath {
    NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    return [filePaths objectAtIndex:0];
}

//获取tmp路径

+ (NSString *)getTmpPath {
    return NSTemporaryDirectory();
}

//获取SystemData路径

+ (NSString *)getSystemDataPath {
    //stringByAppendingString是字符串拼接,拼接路径时要在名称前加“/”
    //stringByAppendingPathComponent是路径拼接,会在字符串前自动添加“/”,成为完整路径
    NSString *path = [NSHomeDirectory() stringByAppendingString:@"/SystemData"];
    //NSString *path = [path stringByAppendingPathComponent:@"SystemData"];
    return path;
}

//获取Preferences路径

+ (NSString *)getPreferencesPath {
    NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSPreferencePanesDirectory, NSUserDomainMask, YES);
    return [filePaths objectAtIndex:0];
}

//获取Caches路径

+ (NSString *)getCachesPath {
    NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return [filePaths objectAtIndex:0];
}

//根据文件路径获取文件名称

+ (NSString *)getFileNameWithPath:(NSString *)path {
    NSArray *array= [path componentsSeparatedByString:@"/"];
    if (array.count == 0) {
        return path;
    }
    return [array objectAtIndex:array.count-1];
}

//根据文件名获取资源文件路径

+ (NSString *)getResourcesFileWithName:(NSString *)name {
    return [[NSBundle mainBundle] pathForResource:name ofType:nil];
}

//判断文件是否存在于某个路径中

+ (BOOL)fileIsExistOfPath:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager fileExistsAtPath:path];
}

//从某个路径中移除文件

+ (BOOL)removeFileOfPath:(NSString *)path {
    BOOL flag = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
      BOOL isExist = [fileManager fileExistsAtPath:path];
    if (isExist) {
        NSError *error;
        BOOL isRemoveSuccess = [fileManager removeItemAtPath:path error:&error];
        if (!isRemoveSuccess) {
            flag = NO;
        }
    }
    return flag;
}

//从URL路径中移除文件

+ (BOOL)removeFileOfURL:(NSURL *)fileURL {
    BOOL isSuccess = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isExist = [fileManager fileExistsAtPath:fileURL.path];
    if (isExist) {
        NSError *error;
        isSuccess = [fileManager removeItemAtURL:fileURL error:&error];
        if (!isSuccess) {
            NSLog(@"removeFileOfURL Failed. errorInfo:%@",error);
        }
    }
    return isSuccess;
}

//创建创建文件夹/目录

+ (BOOL)creatFileDirectoryWithPath:(NSString *)path {
    BOOL isSuccess = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isExist = [fileManager fileExistsAtPath:path];
    if (!isExist) {
        NSError *error;
        isSuccess = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
        if (!isSuccess) {
            NSLog(@"creatFileDirectoryWithPath Failed. errorInfo:%@",error);
        }
    }
    return isSuccess;
}

//创建待写入的空文件:如test.xlArchiver

+ (BOOL)creatFileWithPath:(NSString *)path {
    BOOL isSuccess = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isExist = [fileManager fileExistsAtPath:path];
    if (isExist) {
        return YES;
    }
    NSError *error;
    //stringByDeletingLastPathComponent:删除最后一个路径节点
    NSString *dirPath = [path stringByDeletingLastPathComponent];
    isSuccess = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error];
    if (error) {
        NSLog(@"creatFileWithPath Failed. errorInfo:%@",error);
    }
    if (!isSuccess) {
        return isSuccess;
    }
    isSuccess = [fileManager createFileAtPath:path contents:nil attributes:nil];
    return isSuccess;
}

//保存文件

+ (BOOL)saveFile:(NSString *)filePath withData:(NSData *)data {
    BOOL isSuccess = YES;
    isSuccess = [self creatFileWithPath:filePath];
    if (isSuccess) {
        isSuccess = [data writeToFile:filePath atomically:YES];
        if (!isSuccess) {
            NSLog(@"%s Failed",__FUNCTION__);
        }
    } else {
        NSLog(@"%s Failed",__FUNCTION__);
    }
    return isSuccess;
}

//追加写文件

+ (BOOL)appendData:(NSData *)data withPath:(NSString *)path {
    BOOL result = [self creatFileWithPath:path];
    if (result) {
        NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:path];
        [handle seekToEndOfFile];
        [handle writeData:data];
        [handle synchronizeFile];
        [handle closeFile];
        return YES;
    } else {
        NSLog(@"%s Failed",__FUNCTION__);
        return NO;
    }
}

//获取文件

+ (NSData *)getFileDataWithPath:(NSString *)path {
    NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
    NSData *fileData = [handle readDataToEndOfFile];
   [handle closeFile];
   return fileData;
}

//读取文件

+ (NSData *)getFileDataWithPath:(NSString *)path startIndex:(long long)startIndex length:(NSInteger)length {
    NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
    [handle seekToFileOffset:startIndex];
    NSData *data = [handle readDataOfLength:length];
    [handle closeFile];
    return data;
}

//移动文件

+ (BOOL)moveFileFromPath:(NSString *)fromPath toPath:(NSString *)toPath {
    BOOL isSuccess = YES;
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:fromPath]) {
        NSLog(@"Error: fromPath Not Exist");
        return NO;
    }
    if (![fileManager fileExistsAtPath:toPath]) {
        NSLog(@"Error: toPath Not Exist");
        return NO;
    }
    NSString *headerComponent = [toPath stringByDeletingLastPathComponent];
    if ([self creatFileWithPath:headerComponent]) {
        isSuccess = [fileManager moveItemAtPath:fromPath toPath:toPath error:&error];
        if (!isSuccess) {
            NSLog(@"moveFileFromPath:toPath: Failed. errorInfo:%@", error);
        }
        return isSuccess;
    } else {
        return NO;
    }
}

//拷贝文件

+ (BOOL)copyFileFromPath:(NSString *)fromPath toPath:(NSString *)toPath {
    BOOL isSuccess = YES;
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:fromPath]) {
        NSLog(@"Error: fromPath Not Exist");
        return NO;
    }
    if (![fileManager fileExistsAtPath:toPath]) {
        NSLog(@"Error: toPath Not Exist");
        return NO;
    }
    NSString *headerComponent = [toPath stringByDeletingLastPathComponent];
    if ([self creatFileWithPath:headerComponent]) {
        isSuccess = [fileManager copyItemAtPath:fromPath toPath:toPath error:&error];
        if (!isSuccess) {
             NSLog(@"copyFileFromPath:toPath: Failed. errorInfo:%@", error);
        }
        return isSuccess;
    } else {
        return NO;
    }
}

//重命名文件或目录

//判断对象为空
UIKIT_STATIC_INLINE BOOL StrIsEmpty(id aItem) {
    return aItem == nil
    || ([aItem isKindOfClass:[NSNull class]])
    || (([aItem respondsToSelector:@selector(length)])
    && ([aItem length] == 0))
    || (([aItem respondsToSelector:@selector(count)])
    && ([aItem count] == 0));
}
+ (BOOL)reNameFileWithPath:(NSString *)path toName:(NSString *)toName {
    BOOL isSuccess = YES;
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //获取文件名: 如 视频.MP4
    NSString *lastPathComponent = [path lastPathComponent];
    //获取后缀:MP4
    NSString *pathExtension = [path pathExtension];
    //用传过来的路径创建新路径 首先去除文件名
    NSString *aimPath = [path stringByReplacingOccurrencesOfString:lastPathComponent withString:@""];
    //对文件重命名
    NSString *moveToPath;
    if (StrIsEmpty(pathExtension)) {//没有后缀
        moveToPath = [NSString stringWithFormat:@"%@%@",aimPath, toName];
    } else {
        moveToPath = [NSString stringWithFormat:@"%@%@.%@",aimPath, toName ,pathExtension];
    }
    //通过移动该文件对文件重命名
    isSuccess = [fileManager moveItemAtPath:path toPath:moveToPath error:&error];
    if (!isSuccess){
        NSLog(@"reNameFileWithPath:toName: Failed, errorInfo:%@",error);
    } else {
        NSLog(@"reName success");
    }
    return isSuccess;
}

//获取文件夹下文件列表---该路径下所有目录

+ (NSArray *)getFileListInFolderWithPath:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *fileList = [fileManager contentsOfDirectoryAtPath:path error:&error];
    if (error) {
        NSLog(@"getFileListInFolderWithPath Failed, errorInfo:%@",error);
    }
    return fileList;
}

//获取文件目录下所有文件

+ (NSArray *)getAllFloderWithPath:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *fileAndFloderArr = [self getFileListInFolderWithPath:path];
    NSMutableArray *dirArray = [NSMutableArray new];
    BOOL isDir = NO;
    //在上面那段程序中获得的fileList中列出文件夹名
    for (NSString * file in fileAndFloderArr){
        NSString *paths = [path stringByAppendingPathComponent:file];
        [fileManager fileExistsAtPath:paths isDirectory:(&isDir)];
        if (isDir) {
            [dirArray addObject:file];
        }
        isDir = NO;
    }
    return dirArray;
}

//获取文件大小

+ (int64_t)getFileSizeWithPath:(NSString *)path {
    /*
    unsigned long long fileLength = 0;
    NSNumber *fileSize;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];
    if ((fileSize = [fileAttributes objectForKey:NSFileSize])) {
        fileLength = [fileSize unsignedLongLongValue];
    }
    return fileLength;
    */
    NSDirectoryEnumerator *pathEnum = [[NSFileManager defaultManager] enumeratorAtPath:path];
    NSString *eName;
    int64_t fileSize = 0;
    while (eName = [pathEnum nextObject]){
        //NSLog(@"eName:%@",eName);
        NSDictionary *currentdict = [pathEnum fileAttributes];
        NSString     *filesize = [NSString stringWithFormat:@"%@",[currentdict objectForKey:NSFileSize]];
        NSString     *filetype = [currentdict objectForKey:NSFileType];
        if([filetype isEqualToString:NSFileTypeDirectory]) {
            continue;
        }
        fileSize = fileSize + [filesize longLongValue];
    }
    return fileSize;

}

//获取文件创建时间

+ (NSString *)getFileCreatDateWithPath:(NSString *)path {
    NSError  *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:&error];
    if (error) {
        NSLog(@"getFileCreatDateWithPath Failed, errorInfo:%@",error);
    }
    NSString *date = [fileAttributes objectForKey:NSFileCreationDate];
    return date;
}

//获取文件更改时间

+ (NSString *)getFileChangeDateWithPath:(NSString *)path {
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:&error];
    if (error) {
        NSLog(@"getFileChangeDateWithPath Failed, errorInfo:%@",error);
    }
    NSString *date = [fileAttributes objectForKey:NSFileModificationDate];
    return date;
}

//获取文件所有者

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

推荐阅读更多精彩内容