iOS 文件操作簡介

級別: ★★☆☆☆
標簽:「iOS 文件操作」「SandBox」「QiFileManager」
作者: dac_1033
審校: QiShare團隊

在iOS開發過程中,網絡出錯沒有返回正確數據時有發生,這時可以讀取本地數據展示給用戶來優化用戶體驗,并且在網絡請求正常時及時更新這些本地數據,這些本地數據一般都存在沙盒目錄的文件中,下面我們就來簡單介紹一下iOS開發中的文件操作。附:蘋果官方文件系統編程指南。

一、 關于iOS文件系統

1.1 沙盒(SandBox)

iOS中每個app都有個獨立、封閉、安全的目錄,叫做沙盒,它一般存放著程序包文件(可執行文件)、圖片、音頻、視頻、plist文件、SQLite數據庫以及其他文件。每個app的沙盒都是獨立的,應用程序之間是不可以直接互相訪問的。蘋果官網將沙盒結構劃分為三類(Bundle ContainerData ContaineriClound Container),如下圖:

app沙盒的結構

上圖中的沙盒結構其實是與小編的理解有出入的,具體的沙盒結構我們暫且不做研究。在開發iOS應用程序過程中,我們只能看到沙盒中的根目錄及默認生成的三個文件夾DocumentsLibraryTmp,這些才是我們關注的重點, 關于常用目錄的描述如下:

目錄 描述
AppName.app 應用程序的程序包目錄,包含應用程序的本身。由于應用程序必須經過簽名,所以不能在運行時對這個目錄中的內容進行修改,否則會導致應用程序無法啟動。
Documents/ 保存應用程序的重要數據文件和用戶數據文件等。用戶數據基本上都放在這個位置(例如從網上下載的圖片或音樂文件),該文件夾在應用程序更新時會自動備份,在連接iTunes時也可以自動同步備份其中的數據;
該目錄的內容被iTunes和iCloud備份。
Library/ 這個目錄下有兩個子目錄,可創建子文件夾。可以用來放置您希望被備份但不希望被用戶看到的數據。該路徑下的文件夾,除Caches以外,都會被iTunes備份;
該目錄的內容被iTunes和iCloud備份
Library/Caches 保存應用程序使用時產生的支持文件和緩存文件(保存應用程序再次啟動過程中需要的信息),還有日志文件最好也放在這個目錄;
iTunes 不會備份該目錄,并且該目錄下數據可能被其他工具清理掉。
Library/Preferences 保存應用程序的偏好設置文件。NSUserDefaults類創建的數據和plist文件都放在這里;
該目錄的內容被iTunes和iCloud備份。
Tmp/ 使用此目錄可以編寫在應用程序啟動之間不需要保留的臨時文件,您的應用程序應在不再需要時刪除此目錄中的文件,但是,當您的應用未運行時,系統可能會清除此目錄;
iTunes或iCloud不會備份此目錄下的內容。
1.2 獲取沙盒目錄
- (void)testSandBoxDirectory {
    
    // 獲取app沙盒的根目錄(home)
    NSString *homePath = NSHomeDirectory();
    NSLog(@"NSHomeDirectory: %@", homePath);
    
    // 獲取temp路徑
    NSString *tmp = NSTemporaryDirectory( );
    NSLog(@"NSTemporaryDirectory: %@", tmp);
    
    // 獲取Document目錄
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docPath = [paths lastObject];
    NSLog(@"NSDocumentDirectory: %@", docPath);
    
    // 獲取Library目錄
    paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *libPath = [paths lastObject];
    NSLog(@"NSLibraryDirectory: %@", libPath);
    
    // 獲取Library中的Cache
    paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachesPath = [paths lastObject];
    NSLog(@"NSCachesDirectory: %@", cachesPath);
}
1.3 常用的路徑處理方法

系統在類NSPathUtilities中實現了對NSString的擴展NSString (NSStringPathExtensions),其中定義了很多方法專門用于處理路徑:

- (NSArray *)pathComponents;
- (NSString *)lastPathComponent;
- (NSString *)stringByDeletingLastPathCpmponent;
- (NSString *)stringByAppendingPathConmponent:(NSString *)str;
- (NSString *)pathExtension;
- (NSString *)stringByDeletingPathExtension;
- (NSString *)stringByAppendingPathExtension:(NSString *)str;
1.4 iOS工程中的NSBundle
工程中的bundle文件

如圖,我們自己在工程中創建了一個Test.bundlebundle是一個目錄,其中包含程序會使用到的資源(如圖像、聲音、代碼文件、nib文件等)。在系統中app本身和其他文件沒有什么區別,app包中實際上包含了nib文件、編譯連接過的代碼和其他資源的目錄,我們把app包這個目錄叫做該app的main bundle。在iOS開發中可以使用NSBundle類來操作bundle及其中的資源。NSBundle的官方文檔描述
使用NSBundle的示例代碼如下:

// 獲取main bundle
NSBundle *mainBundle = [NSBundle mainBundle];

// 放在app mainBundle中的自定義Test.bundle
NSString *testBundlePath = [mainBundle pathForResource:@"Test" ofType:@"bundle"];
NSBundle *testBundle = [NSBundle bundleWithPath:testBundlePath];

// 獲取Test.bundle中資源
NSString *resPath = [testBundle pathForResource:@"sound02" ofType:@"wav"];
NSLog(@"自定義bundle中資源的路徑: %@", resPath);
    
// 直接根據目錄獲取資源
UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"Test.bundle/%@", @"logo_img_02"]];
NSLog(@"自定義bundle中圖片: %@", img);

二、文件操作

2.1 文件路徑及文件
// 獲取沙盒根路徑
+ (NSString *)getHomePath {
    
    return NSHomeDirectory();
}

// 獲取tmp路徑
+ (NSString *)getTmpPath {
    
    return NSTemporaryDirectory();
}

// 獲取Documents路徑
+ (NSString *)getDocumentsPath {
    
    NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [pathArr firstObject];
    return path;
}

// 獲取Library路徑
+ (NSString *)getLibraryPath {
    
    NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path = [pathArr firstObject];
    return path;
}

// 獲取LibraryCache路徑
+ (NSString *)getLibraryCachePath {
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *path = [paths firstObject];
    return path;
}

// 檢查文件、文件夾是否存在
+ (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDir {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL exist = [fileManager fileExistsAtPath:path isDirectory:isDir];
    return exist;
}

// 創建路徑
+ (void)createDirectory:(NSString *)path {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir;
    BOOL exist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
    if (!isDir) {
        [fileManager removeItemAtPath:path error:nil];
        exist = NO;
    }
    if (!exist) {
        // 注:直接創建不會覆蓋原文件夾
        [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
}

// 創建文件
+ (NSString *)createFile:(NSString *)filePath fileName:(NSString *)fileName {
    
    // 先創建路徑
    [self createDirectory:filePath];
    
    // 再創建路徑上的文件
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [filePath stringByAppendingPathComponent:fileName];
    BOOL isDir;
    BOOL exist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
    if (isDir) {
        [fileManager removeItemAtPath:path error:nil];
        exist = NO;
    }
    if (!exist) {
        // 注:直接創建會被覆蓋原文件
        [fileManager createFileAtPath:path contents:nil attributes:nil];
    }
    return path;
}

// 復制 文件or文件夾
+ (void)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    BOOL result = [fileManager copyItemAtPath:srcPath toPath:dstPath error:&error];
    if (!result && error) {
        NSLog(@"copyItem Err : %@", error.description);
    }
}

// 移動 文件or文件夾
+ (void)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    BOOL result = [fileManager moveItemAtPath:srcPath toPath:dstPath error:&error];
    if (!result && error) {
        NSLog(@"moveItem Err : %@", error.description);
    }
}

// 刪除 文件or文件夾
+ (void)removeItemAtPath:(NSString *)path {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    BOOL result = [fileManager removeItemAtPath:path error:&error];
    if (!result && error) {
        NSLog(@"removeItem Err : %@", error.description);
    }
}

// 獲取目錄下所有內容
+ (NSArray *)getContentsOfDirectoryAtPath:(NSString *)docPath {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *contentArr = [fileManager contentsOfDirectoryAtPath:docPath error:&error];
    if (!contentArr.count && error) {
        NSLog(@"ContentsOfDirectory Err : %@", error.description);
    }
    return contentArr;
}
2.2 能直接進行文件讀寫的數據類型

iOS中有四種簡單類型能夠直接進行文件讀寫:字符串NSString/NSMutableString、數組NSArray/NSMutableArray、字典NSDictionary/NSMutableDictionary、二進制數據NSData/NSMutableData
代碼示例如下:

NSString *string = @"QiShare test string ...";
[string writeToFile:path11 atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSString *readStr = [NSString stringWithContentsOfFile:path11 encoding:NSUTF8StringEncoding error:nil];
NSLog(@"讀取文件-字符串: %@", readStr);
    
NSArray *array = @[@"Q", @"i", @"S", @"h", @"a", @"r", @"e"];
[array writeToFile:path33 atomically:YES];
NSArray *readArr = [NSArray arrayWithContentsOfFile:path33];
NSLog(@"讀取文件-數組: %@", readArr);
    
NSDictionary *dict = @{@"en":@"QiShare", @"ch":[[FileUtil alloc] init]};
[dict writeToFile:path34 atomically:YES];
NSDictionary *readDict = [NSDictionary dictionaryWithContentsOfFile:path34];
NSLog(@"讀取文件-字典: %@", readDict);
    
NSData *data = [@"QiShare test data ..." dataUsingEncoding:NSUTF8StringEncoding];
[data writeToFile:path11 atomically:YES];
NSData *readData = [NSData dataWithContentsOfFile:path11];
NSLog(@"讀取文件-二進制: %@", readData);
  • 其中數組和字典中的元素對象的類型也必須是上述四種,否則不能直接寫入文件;
  • 每次調用writeToFile:方法寫入文件時,都會覆蓋文件原有內容。

三、文件內容操作

iOS開發在涉及到文件操作的過程中,進行一些細粒度的文件內容操作時會用到NSFileHandle。一般用NSFileHandle修改文件內容有三個步驟:打開文件,獲取一個NSFileHandle對象;對打開文件執行相關操作;關閉文件。NSFileHandle具體功能概括如下:

  • 打開一個文件,執行讀、寫或更新操作;
  • 在文件中查找指定位置;
  • 從文件中讀取特定數目的字節,或將特定數目的字節寫入文件中;
  • NSFileHandle類提供的方法也可以用于各種設備或套接字。

NSFileHandle操作文件內容示例代碼如下:

// NSFileHandle操作文件內容
- (void)testFileHandle {
    
    NSString *docPath = [FileUtil getDocumentsPath];
    NSString *readPath = [docPath stringByAppendingPathComponent:@"read.txt"];
    NSString *writePath = [docPath stringByAppendingPathComponent:@"write.txt"];
    NSData *data = [@"abcdefghijklmnopqrstuvwxyz" dataUsingEncoding:NSUTF8StringEncoding];
    
    NSFileManager *manager=[NSFileManager defaultManager];
    [manager createFileAtPath:readPath contents:data attributes:nil];
    [manager createFileAtPath:writePath contents:nil attributes:nil];
    [data writeToFile:readPath atomically:YES];
    
    // 打開文件 讀
    NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:readPath];
    NSData *readData = [readHandle readDataToEndOfFile];
    
    // 讀取文件中指定位置/指定長度的內容
    [readHandle seekToFileOffset:10];
    readData = [readHandle readDataToEndOfFile];
    NSLog(@"seekToFileOffset:10 = %@", [[NSString alloc] initWithData:readData encoding:NSUTF8StringEncoding]);
    
    [readHandle seekToFileOffset:10];
    readData = [readHandle readDataOfLength:5];
    NSLog(@"seekToFileOffset:10 = %@",[[NSString alloc]initWithData:readData encoding:NSUTF8StringEncoding]);
    [readHandle closeFile];
    
    // 打開文件 寫
    NSFileHandle *writeHandle = [NSFileHandle fileHandleForWritingAtPath:writePath];
    // 注:直接覆蓋文件原有內容
    [writeHandle writeData:data];
    
    // 注:覆蓋了指定位置/指定長度的內容
    [writeHandle seekToFileOffset:2];
    [writeHandle writeData:[@"CDEFG" dataUsingEncoding:NSUTF8StringEncoding]];
    
    [writeHandle seekToEndOfFile];
    [writeHandle writeData:[@"一二三四五六" dataUsingEncoding:NSUTF8StringEncoding]];
    [writeHandle closeFile];
}

工程源碼地址:GitHub地址


推薦文章:
iOS 關鍵幀動畫
iOS 獲取設備當前語言和地區
iOS 編寫高質量Objective-C代碼(七)

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。