萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 檢測檔案是否存在的 4 種方法完整對比

前言:存在性檢查是檔案操作的前置動作

讀寫、移動、刪除前確認檔案存在,避免例外與錯誤。iOS 提供多種檢查方式,適用場景不同。

方法一:NSBundle 主包資源檢查(唯讀資源)


// 適用:App Bundle 內的唯讀資源(圖片、Plist、JSON 等)
NSString *path = [[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"];
if (path) {
    // 存在,path 為完整路徑
    NSDictionary *config = [NSDictionary dictionaryWithContentsOfFile:path];
} else {
    // 不存在於 Bundle
}

特點:自動處理本地化目錄(如 `zh-Hans.lproj/config.plist`)、不需完整路徑、只能查 Bundle 內資源。

方法二:NSFileManager fileExistsAtPath:(通用標準)


// 適用:沙盒任意路徑(Documents、Caches、tmp 等)
NSFileManager *fm = [NSFileManager defaultManager];
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject];
NSString *filePath = [docPath stringByAppendingPathComponent:@"user.plist"];

if ([fm fileExistsAtPath:filePath]) {
    NSLog(@"檔案存在");
    // 進一步判斷是檔案還是目錄
    BOOL isDir = NO;
    [fm fileExistsAtPath:filePath isDirectory:&isDir];
    if (isDir) NSLog(@"是目錄");
} else {
    NSLog(@"檔案不存在");
}

特點:最通用、可區分檔案/目錄、支援完整路徑、效能佳。

方法三:自定義工具類封裝(專案通用)


// FileUtil.h
@interface FileUtil : NSObject
+ (BOOL)fileExistsAtPath:(NSString *)path;
+ (BOOL)fileExistsInDocuments:(NSString *)fileName;
+ (BOOL)fileExistsInCaches:(NSString *)fileName;
@end

// FileUtil.m
@implementation FileUtil
+ (BOOL)fileExistsAtPath:(NSString *)path {
    return [[NSFileManager defaultManager] fileExistsAtPath:path];
}

+ (BOOL)fileExistsInDocuments:(NSString *)fileName {
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject]
                      stringByAppendingPathComponent:fileName];
    return [self fileExistsAtPath:path];
}

+ (BOOL)fileExistsInCaches:(NSString *)fileName {
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject]
                      stringByAppendingPathComponent:fileName];
    return [self fileExistsAtPath:path];
}
@end

// 使用
if ([FileUtil fileExistsInDocuments:@"user.plist"]) {
    // 存在
}

方法四:實例方法封裝(ViewController 內部使用)


- (BOOL)judgeFileExist:(NSString *)fileName {
    // 從 Bundle 尋找
    NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@""];
    if (path) return YES;
    
    // 從 Documents 尋找
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docPath = [[paths.firstObject stringByAppendingPathComponent:fileName]];
    return [[NSFileManager defaultManager] fileExistsAtPath:docPath];
}

完整範例:圖片快取「存在則讀本地,不存在則下載」


- (void)loadImageWithCache:(NSString *)imageName urlString:(NSString *)urlString {
    // 1. 定義儲存路徑
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *dirPath = [[paths.firstObject stringByAppendingPathComponent:@"ImageCache"] 
                         stringByAppendingPathComponent:imageName];
    
    NSData *imageData = nil;
    
    // 2. 檢查本地快取
    if ([[NSFileManager defaultManager] fileExistsAtPath:dirPath]) {
        NSLog(@"命中本地快取: %@", dirPath);
        imageData = [NSData dataWithContentsOfFile:dirPath];
    } else {
        NSLog(@"快取未命中,下載: %@", urlString);
        // 3. 下載(實際專案請用異步 NSURLSession)
        NSURL *url = [NSURL URLWithString:urlString];
        imageData = [NSData dataWithContentsOfURL:url]; // 同步示範
        
        if (imageData) {
            // 4. 確保目錄存在
            NSString *dir = [dirPath stringByDeletingLastPathComponent];
            [[NSFileManager defaultManager] createDirectoryAtPath:dir 
                                            withIntermediateDirectories:YES 
                                             attributes:nil 
                                                  error:nil];
            // 5. 寫入檔案
            [imageData writeToFile:dirPath atomically:YES];
        }
    }
    
    // 6. 顯示
    if (imageData) {
        self.imageView.image = [UIImage imageWithData:imageData];
    }
}

方法對比總結表

方法適用範圍是否區分檔案/目錄效能推薦指數
NSBundle pathForResource:Bundle 唯讀資源否(僅檔案)快⭐⭐⭐⭐⭐ (Bundle資源首選)
NSFileManager fileExistsAtPath:沙盒任意路徑是 (isDirectory:)快⭐⭐⭐⭐⭐ (通用首選)
自定義工具類專案統一封裝視封裝快⭐⭐⭐⭐ (團隊協作推薦)
實例方法封裝單一類別內部視實作快⭐⭐⭐ (快速原型)

避坑提醒

  1. TOCTOU 競態:檢查存在 → 實際操作間隙檔案可能被刪。關鍵操作請直接嘗試操作並處理錯誤,而非先檢查。
  2. 路徑拼接:務必用 `stringByAppendingPathComponent:`,手動拼接 `/` 極易出錯。
  3. 大小寫敏感**:真機檔案系統區分大小寫,模擬器不區分。測試必須真機。
  4. NSURL vs NSString 路徑**:API 混用易出錯,統一用 `NSString` 路徑或 `NSURL` 檔案 URL。
copyright © 萬盛學電腦網 all rights reserved