天天看點

iOS開發之檔案操作(一個簡單的檔案操作類)

在開發應用程式中,不可避免的會使用到檔案讀寫操作,如何才能高效省力的來處理這些操作呢!那就是把一些常用的檔案操作流程寫進一個工具類中,每次要用的時候

就直接導入檔案,接口調用就可以啦!下面是我寫的一個檔案操作類。

#import "FileUtil.h"

@implementation FileUtil

/*檔案是否存在*/
+ (BOOL)isFileExisted:(NSString *)fileName{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:[self getFilePath:fileName]]){
        return NO;
    }
    
    return YES;
}

/*建立指定名字的檔案*/
+ (BOOL)createFileAtPath:(NSString *)fileName{
    NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[array objectAtIndex:0] stringByAppendingPathComponent:fileName];
    NSLog(@"-----%@:", path);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:path]){
        [fileManager createFileAtPath:path contents:nil attributes:nil];
        return YES;
    }
    
    return NO;
}

/*建立指定名字的檔案夾*/
+ (BOOL)createDirectoryAtPath:(NSString *)fileName{
    NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[array objectAtIndex:0] stringByAppendingPathComponent:fileName];
    NSLog(@"-----%@:", path);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:path]){
        NSError *error = nil;
        [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
        return YES;
    }
    
    return NO;
}

/*得到檔案路徑*/
+ (NSString *)getFilePath:(NSString *)fileName{
    NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[array objectAtIndex:0] stringByAppendingPathComponent:fileName];
    
    return path;
}

/*删除檔案*/
+ (BOOL)deleteFileAtPath:(NSString *)fileName{
    NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[array objectAtIndex:0] stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if(![fileManager fileExistsAtPath:path]){
        return NO;
    }
    
    [fileManager removeItemAtPath:path error:nil];
    return YES;
}

/*得到PList檔案*/
+ (NSMutableDictionary *)getPlistFile:(NSString *)fileName{

    NSBundle *bundle = [NSBundle mainBundle];
    NSString *path = [bundle pathForResource:fileName ofType:@"plist"];
    
    return [[NSMutableDictionary alloc] initWithContentsOfFile:path];
}

/*擷取plist檔案目錄*/
+ (NSString *)getPListFilePath:(NSString *)fileName{
    NSBundle *bundle = [NSBundle mainBundle];
    return [bundle pathForResource:fileName ofType:@"plist"];
}

@end
           

是不是很簡單粗暴啊!:)

繼續閱讀