iOS 文件(NSFileManager)及 文件內(nèi)容(NSFileHandle) 基礎(chǔ)使用

NSFileManager

此類主要是對(duì)文件進(jìn)行的操作以及文件信息的獲取

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

+ (BOOL)fileIsExistOfPath:(NSString *)filePath
{
    BOOL flag = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        flag = YES;
    } else {
        flag = NO;
    }
    return flag;
}

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

+ (BOOL)removeFileOfPath:(NSString *)filePath
{
    BOOL flag = YES;
    NSFileManager *fileManage = [NSFileManager defaultManager];
    if ([fileManage fileExistsAtPath:filePath]) {
        if (![fileManage removeItemAtPath:filePath error:nil]) {
            flag = NO;
        }
    }
    return flag;
}

從URL路徑中移除文件

- (BOOL)removeFileOfURL:(NSURL *)fileURL
{
    BOOL flag = YES;
    NSFileManager *fileManage = [NSFileManager defaultManager];
    if ([fileManage fileExistsAtPath:fileURL.path]) {
        if (![fileManage removeItemAtURL:fileURL error:nil]) {
            flag = NO;
        }
    }
    return flag;
}

創(chuàng)建文件夾

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

創(chuàng)建文件

+ (BOOL)creatFileWithPath:(NSString *)filePath
{
    BOOL isSuccess = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL temp = [fileManager fileExistsAtPath:filePath];
    if (temp) {
        return YES;
    }
    NSError *error;
    //stringByDeletingLastPathComponent:刪除最后一個(gè)路徑節(jié)點(diǎn)
    NSString *dirPath = [filePath stringByDeletingLastPathComponent];
    isSuccess = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error];
    if (error) {
        NSLog(@"creat File Failed. errorInfo:%@",error);
    }
    if (!isSuccess) {
        return isSuccess;
    }
    isSuccess = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    return isSuccess;
}

保存文件

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

移動(dòng)文件

+ (BOOL)moveFileFromPath:(NSString *)fromPath toPath:(NSString *)toPath
{
    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]) {
        return [fileManager moveItemAtPath:fromPath toPath:toPath error:nil];
    } else {
        return NO;
    }
}

拷貝文件

+(BOOL)copyFileFromPath:(NSString *)fromPath toPath:(NSString *)toPath
{
    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]) {
        return [fileManager copyItemAtPath:fromPath toPath:toPath error:nil];
    } else {
        return NO;
    }
}

獲取文件夾下文件列表

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

獲取文件大小

+ (long long)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]; //單位是 B
    }
    return fileLength / 1000; 換算為K
}

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

+ (NSString *)getFileCreatDateWithPath:(NSString *)path
{
    NSString *date = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];
    date = [fileAttributes objectForKey:NSFileCreationDate];
    return date;
}

獲取文件所有者

+ (NSString *)getFileOwnerWithPath:(NSString *)path
{
    NSString *fileOwner = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];
    fileOwner = [fileAttributes objectForKey:NSFileOwnerAccountName];
    return fileOwner;
}

獲取文件更改日期

+ (NSString *)getFileChangeDateWithPath:(NSString *)path
{
    NSString *date = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];
    date = [fileAttributes objectForKey:NSFileModificationDate];
    return date;
}

NSFileHandle

此類主要是對(duì)文件內(nèi)容進(jìn)行讀取和寫入操作

// 打開一個(gè)文件準(zhǔn)備讀取
+ (id)fileHandleForReadingAtPath:(NSString *)path  

// 打開一個(gè)文件準(zhǔn)備寫入
+ (id)fileHandleForWritingAtPath:(NSString *)path  

// 打開一個(gè)文件準(zhǔn)備更新
+ (id)fileHandleForUpdatingAtPath:(NSString *)path  

// 從設(shè)備或通道返回可用的數(shù)據(jù)
-  (NSData *)availableData; 

// 從當(dāng)前的節(jié)點(diǎn)讀取到文件的末尾
-  (NSData *)readDataToEndOfFile; 

// 從當(dāng)前節(jié)點(diǎn)開始讀取指定的長(zhǎng)度
-  (NSData *)readDataOfLength:(NSUInteger)length; 


// 寫入數(shù)據(jù)
-  (void)writeData:(NSData *)data; 

// 獲取當(dāng)前文件的偏移量
-  (unsigned long long)offsetInFile;  

// 跳到指定文件的偏移量
-  (void)seekToFileOffset:(unsigned long long)offset; 

// 跳到文件末尾
-  (unsigned long long)seekToEndOfFile; 

// 將文件的長(zhǎng)度設(shè)為offset字節(jié)
-  (void)truncateFileAtOffset:(unsigned long long)offset; 

// 關(guān)閉文件
-  (void)closeFile;  
NSFileHandle使用介紹

向文件追加數(shù)據(jù)

+ (BOOL)appendData:(NSData *)data withPath:(NSString *)path
{
    BOOL result = [self creatFileWithPath:path];
    if (result) {
        NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:path];
        [handle seekToEndOfFile];  將節(jié)點(diǎn)跳到文件的末尾
        [handle writeData:data];      追加寫入數(shù)據(jù)
        [handle synchronizeFile];    同步文件
        [handle closeFile];                關(guān)閉文件
        return YES;
    } else {
        NSLog(@"%s Failed",__FUNCTION__);
        return NO;
    }
}

//獲取文件

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

//讀取文件
+ (NSData *)getFileData:(NSString *)filePath startIndex:(long long)startIndex length:(NSInteger)length
{
    NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:filePath];
    [handle seekToFileOffset:startIndex];
    NSData *data = [handle readDataOfLength:length];
    [handle closeFile];
    return data;
}

說明: 我們對(duì)于一般的圖片資源的儲(chǔ)存,一般都是將圖片轉(zhuǎn)成二進(jìn)制數(shù)據(jù),然后寫入到特定文件夾下的
// stringByAppendingPathComponent 拼接一個(gè)文件路徑會(huì)自動(dòng)在前面加上 '/'
NSString * filePath = [path stringByAppendingPathComponent:@"admin.plist"];

復(fù)制文件

NSFileHandle *infile, *outfile; 輸入文件、輸出文件

NSData *buffer; 讀取的緩沖數(shù)據(jù)

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *homePath = NSHomeDirectory( );

NSString *sourcePath = [homePath stringByAppendingPathComponent:@"testfile.txt"];  源文件路徑

NSString *outPath = [homePath stringByAppendingPathComponent:@"outfile.txt"]; 輸出文件路徑

BOOL sucess  = [fileManager createFileAtPath:outPath contents:nil attributes:nil];

if (!success){
return N0;
}

infile = [NSFileHandle fileHandleForReadingAtPath:sourcePath]; 創(chuàng)建讀取源路徑文件

if (infile == nil){
return NO;
}

outfile = [NSFileHandle fileHandleForReadingAtPath:outPath];創(chuàng)建并打開要輸出的文件

if (outfile == nil){
return NO;
}

[outfile truncateFileAtOffset:0]; 將輸出文件的長(zhǎng)度設(shè)為0

buffer = [infile readDataToEndOfFile];  讀取數(shù)據(jù)

[outfile writeData:buffer];  寫入輸入

[infile closeFile];        關(guān)閉寫入、輸入文件

[outfile closeFile];
文章參考

iOS中NSFileManager文件常用操作整合
iOS NSFileHandle 基本用法介紹

最后編輯于
?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 一、iOS中的沙盒機(jī)制 iOS應(yīng)用程序只能對(duì)自己創(chuàng)建的文件系統(tǒng)讀取文件,這個(gè)獨(dú)立、封閉、安全的空間,叫做沙盒。它一...
    1d5cb7cff98d閱讀 1,873評(píng)論 0 0
  • iOS開發(fā)-文件管理(一) 一、iOS中的沙盒機(jī)制 iOS應(yīng)用程序只能對(duì)自己創(chuàng)建的文件系統(tǒng)讀取文件,這個(gè)獨(dú)立、封閉...
    MacShare閱讀 1,862評(píng)論 0 6
  • 27、ViewController的didReceiveMemoryWarning是在什么時(shí)候調(diào)用的?默認(rèn)的操作是...
    煙雨平生花飛舞閱讀 693評(píng)論 0 1
  • 一、iOS中的沙盒機(jī)制 iOS應(yīng)用程序只能對(duì)自己創(chuàng)建的文件系統(tǒng)讀取文件,這個(gè)獨(dú)立、封閉、安全的空間,叫做沙盒。它一...
    tzhtodd閱讀 1,347評(píng)論 0 2
  • 演唱:莫文蔚 我想親口說再見 你的空位還在這 在開始之前,句點(diǎn)后面 存活在我里面 不散,不見 你是我世界起點(diǎn) 我是...
    芥言諠既閱讀 285評(píng)論 0 0

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