NSFileManager

    xiaoxiao2021-04-13  29

    NSFileManager类主要对文件和目录的操作(删除、修改、移动、复制等等)。如果对文件的内容更改,应该使用NSFileHandle。所以说NSFileManager相对于NSFileHandle偏向于对文件的管理,而不是对内容的操作。

    NSFileManager管理文件

    1. 创建文件
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject; NSString *filePath = [path stringByAppendingPathComponent:@"text"]; if ([[NSFileManager defaultManager]createFileAtPath:filePath contents:nil attributes:nil]) { NSLog(@"文件创建成功"); }else{ NSLog(@"文件创建失败"); }
    2. 文本写入
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject; NSString *filePath = [path stringByAppendingPathComponent:@"text.txt"]; NSString *message = @"hello"; [[NSFileManager defaultManager]createFileAtPath:filePath contents:[message dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES] attributes:nil];
    3. 文本读取
    NSData *data = [[NSFileManager defaultManager]contentsAtPath:filePath]; NSString *text = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    4. 移动文件路径
    [[NSFileManager defaultManager]moveItemAtPath:oldPath toPath:newPath error:NULL];
    5. 复制文件
    [NSFileManager defaultManager]copyItemAtPath:path toPath:newPath error:NULL];
    6. 比较两个文件的内容
    - (BOOL)contentsEqualAtPath:(NSString *)path1 andPath:(NSString *)path2;
    7. 文件是否存在
    - (BOOL)fileExistsAtPath:(NSString *)path;
    8. 删除文件
    - (BOOL)removeItemAtPath:(NSString *)path error:(NSError **) error;
    9. 获取文件大小

    获得文件的属性字典 

    NSDictionary *attrDic = [[NSFileManager defaultManager] attributesOfItemAtpath:sourcePath error:nil]; NSNumber *fileSize = [attrDic objectForKey:NSFileSize];
    10. 测试文件是否存在,且是否能执行读操作
    -BOOLisReadablefileAtPath:path
    11. 测试文件是否存在,且是否能执行写操作
    -BOOLisWritablefileAtPath:path
    附录: 用C语言获取文件的大小

    int getFileSizeFromPath(char * path){ FILE * file; int fileSizeBytes = 0; file = fopen(path,"r"); if(file>0){ fseek(file, 0, SEEK_END); fileSizeBytes = ftell(file); fseek(file, 0, SEEK_SET); fclose(file); } return fileSizeBytes;}

    NSFileManager管理目录

    1. 获取当前目录

    -(NSString *)currentDirectoryPath

    2. 更改当前目录

    -(BOOL)changeCurrentDirectoryPath:path

    3. 复制目录结构,to不能已经存在

    -(BOOL)copyPath:from toPath:to handler:handler

    4. 创建目录

    -(BOOL)createDirectoryAtPath:path attributes:attr

    5. 测试文件是否为目录 (flag存储结构yes/no)

    -(BOOL)fileExistsAtPath:path isDirectory:(BOOL *)flag

    6. 列出目录的内容

    -NSArray *)contentsOfDirectoryAtPath:path

    7. 枚举目录的内容

    -(NSDirectoryEnumerator *)enumeratorAtPath:path

    8. 删除空目录

    -(BOOL)removeFileAtPath:path handlerhandler

    9. 重命名或移动一个目录,to不能是已经存在的

    -BOOLmovePath:from toPath:to handler:handler 文章转自: http://www.jianshu.com/p/186ccef700a9 Hi唐吉柯德
    转载请注明原文地址: https://ju.6miu.com/read-668659.html

    最新回复(0)