數(shù)據(jù)持久化---文件操作相關(guān)方法

//獲取應(yīng)用程序路徑

+ (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是字符串拼接,拼接路徑時(shí)要在名稱前加“/”
    //stringByAppendingPathComponent是路徑拼接,會(huì)在字符串前自動(dòng)添加“/”,成為完整路徑
    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];
}

//根據(jù)文件路徑獲取文件名稱

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

//根據(jù)文件名獲取資源文件路徑

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

//判斷文件是否存在于某個(gè)路徑中

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

//從某個(gè)路徑中移除文件

+ (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;
}

//創(chuàng)建創(chuàng)建文件夾/目錄

+ (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;
}

//創(chuàng)建待寫入的空文件:如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:刪除最后一個(gè)路徑節(jié)點(diǎn)
    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;
}

//移動(dòng)文件

+ (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;
    }
}

//重命名文件或目錄

//判斷對(duì)象為空
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];
    //用傳過(guò)來(lái)的路徑創(chuàng)建新路徑 首先去除文件名
    NSString *aimPath = [path stringByReplacingOccurrencesOfString:lastPathComponent withString:@""];
    //對(duì)文件重命名
    NSString *moveToPath;
    if (StrIsEmpty(pathExtension)) {//沒(méi)有后綴
        moveToPath = [NSString stringWithFormat:@"%@%@",aimPath, toName];
    } else {
        moveToPath = [NSString stringWithFormat:@"%@%@.%@",aimPath, toName ,pathExtension];
    }
    //通過(guò)移動(dòng)該文件對(duì)文件重命名
    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;

}

//獲取文件創(chuàng)建時(shí)間

+ (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;
}

//獲取文件更改時(shí)間

+ (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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容