程序员iOS点点滴滴iOS高级开发

iOS中的文件管理(一)—— NSFileManager基础

2017-04-25  本文已影响506人  指尖书法

最近一直在做文件管理相关的功能,苹果官方提供了一个最主要的接口:NSFileManager,方便在iOS中进行文件管理。本文主要对常用的功能进行整理和归纳,以便学习之用。

NSFileManager 简介

开始使用

  1. 创建一个单例对象
NSFileManager *fileManager = [NSFileManager defaultManager];
  1. 判断文件是否存在
    filePath : NSString类型 表示一个文件的路径
    BOOL isExists = [fileManager fileExistsAtPath:filePath];
  1. 判断目录是否存在
BOOL isDir;
    [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    if (isDir) {
        NSLog(@"这是个目录");
    }else {
        NSLog(@"不是目录");
    }
  1. 判断文件是否可读、可写、可删除 结果都返回BOOL
[fileManager isWritableFileAtPath:filePath];
[fileManager isReadableFileAtPath:filePath];
[fileManager isDeletableFileAtPath:filePath];

获取

  1. 文件属性
    列出常用的文件属性:

       NSFileAttributeKey const NSFileType; :
       NSFileAttributeType const NSFileTypeDirectory;
       NSFileAttributeType const NSFileTypeRegular;
       NSFileAttributeKey const NSFileSize;
       NSFileAttributeKey const NSFileModificationDate;  //修改时间
       NSFileAttributeKey const NSFileCreationDate; //创建时间
    

剩下的在官方文档中查询。

  1. 获取文件属性的两种方式
    (1))attributesOfItem方法获取单个文件的属性字典。
    /**
    获取文件属性

      @param path 文件路径
      @param error 错误信息
      @return 返回一个属性字典
      */
     - (nullable NSDictionary<NSFileAttributeKey, id> *)attributesOfItemAtPath:(NSString *)path error:(NSError **)error;
    

(2)利用文件遍历器获取一个文件夹中所有文件的属性(这个方法是我这次项目使用的关键数据源方法)
//文件属性遍历器
NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtPath:path];

    //遍历属性
    NSString *fileName;
    //下面这个方法最为关键 可以给fileName赋值,获得文件名(带文件后缀)。
    while (fileName = [enumerator nextObject]) {
        //跳过子路径
        [enumerator skipDescendants];
        //获取文件属性
        //enumerator.fileAttributes 的后面可以用点语法点出许多许多的属性。
        NSLog(@"%@",enumerator.fileAttributes);
    }
  1. 获取文件列表
    如果单单获取文件列表名,有个直接的方法:
    - (nullable NSArray<NSString *> *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error;
    但如果还需要其他操作,就用下面两个方法更为科学:

创建与编辑

  1. 创建目录
    一般在判断了目录是否存在之后,若不存在,就会创建一个目录:
    /**
    创建目录

      @param path 路径
      @param createIntermediates YES/NO 创建路径的时候,YES自动创建路径中缺少的目录,NO的不会创建缺少的目录
      @param attributes 属性的字典
      @param error 错误对象
      @return 返回是否成功
      */
     - (BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(nullable NSDictionary<NSString *, id> *)attributes error:(NSError **)error;
    
  2. 创建文件
    [fileManager createFileAtPath:createDirPath contents:data attributes:nil];

  3. 拷贝
    [fileManager copyItemAtPath:createDirPath toPath:targetPath error:nil];

下一篇文章,我会分享在具体使用中的注意点和一些小技巧(如在控制器中的显示、文件排序、大图标、文件预览等等)。

上一篇 下一篇

猜你喜欢

热点阅读