iOS 文件(NSFileManager)及 文件内容(NSFileHandle) 基础使用

NSFileManager

此类主要是对文件进行的操作以及文件信息的获取

判断文件是否存在于某个路径中

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

从某个路径中移除文件

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

创建文件夹

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

创建文件

+ (BOOL)creatFileWithPath:(NSString *)filePath
{
    BOOL isSuccess = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL temp = [fileManager fileExistsAtPath:filePath];
    if (temp) {
        return YES;
    }
    NSError *error;
    //stringByDeletingLastPathComponent:删除最后一个路径节点
    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;
}

移动文件

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

获取文件创建时间

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

此类主要是对文件内容进行读取和写入操作

// 打开一个文件准备读取
+ (id)fileHandleForReadingAtPath:(NSString *)path  

// 打开一个文件准备写入
+ (id)fileHandleForWritingAtPath:(NSString *)path  

// 打开一个文件准备更新
+ (id)fileHandleForUpdatingAtPath:(NSString *)path  

// 从设备或通道返回可用的数据
-  (NSData *)availableData; 

// 从当前的节点读取到文件的末尾
-  (NSData *)readDataToEndOfFile; 

// 从当前节点开始读取指定的长度
-  (NSData *)readDataOfLength:(NSUInteger)length; 


// 写入数据
-  (void)writeData:(NSData *)data; 

// 获取当前文件的偏移量
-  (unsigned long long)offsetInFile;  

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

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

// 将文件的长度设为offset字节
-  (void)truncateFileAtOffset:(unsigned long long)offset; 

// 关闭文件
-  (void)closeFile;  
NSFileHandle使用介绍

向文件追加数据

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

说明: 我们对于一般的图片资源的储存,一般都是将图片转成二进制数据,然后写入到特定文件夹下的
// stringByAppendingPathComponent 拼接一个文件路径会自动在前面加上 '/'
NSString * filePath = [path stringByAppendingPathComponent:@"admin.plist"];

复制文件

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

NSData *buffer; 读取的缓冲数据

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]; 创建读取源路径文件

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

outfile = [NSFileHandle fileHandleForReadingAtPath:outPath];创建并打开要输出的文件

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

[outfile truncateFileAtOffset:0]; 将输出文件的长度设为0

buffer = [infile readDataToEndOfFile];  读取数据

[outfile writeData:buffer];  写入输入

[infile closeFile];        关闭写入、输入文件

[outfile closeFile];
文章参考

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

你可能感兴趣的:(iOS 文件(NSFileManager)及 文件内容(NSFileHandle) 基础使用)