數(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是字符串拼接,拼接路徑時要在名稱前加“/”
    //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];
}

//根據(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];
}

//判斷文件是否存在于某個路徑中

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

//創(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:刪除最后一個路徑節(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;
}

//移動文件

+ (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];
    //用傳過來的路徑創(chuàng)建新路徑 首先去除文件名
    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;

}

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

+ (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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末陋率,一起剝皮案震驚了整個濱河市逢唤,隨后出現(xiàn)的幾起案子兽愤,更是在濱河造成了極大的恐慌,老刑警劉巖狞尔,帶你破解...
    沈念sama閱讀 216,651評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件肥缔,死亡現(xiàn)場離奇詭異莲兢,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)续膳,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評論 3 392
  • 文/潘曉璐 我一進(jìn)店門改艇,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人坟岔,你說我怎么就攤上這事谒兄。” “怎么了社付?”我有些...
    開封第一講書人閱讀 162,931評論 0 353
  • 文/不壞的土叔 我叫張陵承疲,是天一觀的道長。 經(jīng)常有香客問我鸥咖,道長燕鸽,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,218評論 1 292
  • 正文 為了忘掉前任啼辣,我火速辦了婚禮啊研,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己党远,他們只是感情好削解,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,234評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著沟娱,像睡著了一般钠绍。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上花沉,一...
    開封第一講書人閱讀 51,198評論 1 299
  • 那天,我揣著相機(jī)與錄音媳握,去河邊找鬼碱屁。 笑死,一個胖子當(dāng)著我的面吹牛粒竖,可吹牛的內(nèi)容都是我干的筷登。 我是一名探鬼主播擅耽,決...
    沈念sama閱讀 40,084評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼柿赊!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起幻枉,我...
    開封第一講書人閱讀 38,926評論 0 274
  • 序言:老撾萬榮一對情侶失蹤碰声,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后熬甫,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體胰挑,經(jīng)...
    沈念sama閱讀 45,341評論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,563評論 2 333
  • 正文 我和宋清朗相戀三年椿肩,在試婚紗的時候發(fā)現(xiàn)自己被綠了瞻颂。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,731評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡郑象,死狀恐怖贡这,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情厂榛,我是刑警寧澤盖矫,帶...
    沈念sama閱讀 35,430評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站噪沙,受9級特大地震影響炼彪,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜正歼,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,036評論 3 326
  • 文/蒙蒙 一辐马、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦喜爷、人聲如沸冗疮。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽术幔。三九已至,卻和暖如春湃密,著一層夾襖步出監(jiān)牢的瞬間诅挑,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評論 1 269
  • 我被黑心中介騙來泰國打工泛源, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留拔妥,地道東北人。 一個月前我還...
    沈念sama閱讀 47,743評論 2 368
  • 正文 我出身青樓达箍,卻偏偏與公主長得像没龙,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子缎玫,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,629評論 2 354

推薦閱讀更多精彩內(nèi)容