iOS 关于NSFileManager的搜集

来源:互联网 发布:java怎么调用构造函数 编辑:程序博客网 时间:2024/05/16 23:55

转自:http://www.jianshu.com/p/3355373e0b81


使用NSFileManager

  • 文件系统接口
  • 允许访问文件夹内容
  • 创建,重命名,删除文件,修改文件和文件属性,以及Finder对所有文件系统任务执行的一般操作
  • 访问NSFileManager,使用共享的管理器对象
    • NSFileManager *fileManager = [NSFileManager defaultManager];
  • 允许对NSFileManager设置代理

    • 用于当文件管理器完成如复制或移动文件操作时,接受相应的信息
    • 需要创建自己的NSFileManager实例,而不是使用共享实例

        NSFileManager *newFileManager = [[NSFileManager alloc] init];  newFileManager.delegate = self;
  • 获取一个文件夹的内容

    • contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:
    • 简单返回文件夹内容的NSURL

        NSURL *folderURL = [NSURL fileURLWithPath:@"/Applications/"];  NSFileManager *fileManager = [NSFileManager defaultManager];  NSError *error = nil;  NSArray *folderContents = [fileManager   contentsOfDirectoryAtURL:folderURL  includingPropertiesForKeys:nil  options:0  error:error];
    • folderContents包含指向该文件夹中每一项的NSURL

  • 访问单独的NSURL对象,获取指向的文件信息

    • resourceValuesForKeys:error:
    • 返回NSDictionary,包含每一项指向的文件的属性

        //新建一个数组,包含想要了解的属性  //这里包含文件大小,修改日期  NSArray *attributes = [NSArray arrayWithObjects:NSURLFileSizeKey,NSURLContentModificationDateKey,nil];  //获得返回的结果  //anURL是一个NSURL对象,想要了解的文件(夹)  //这里不关心出错信息  NSDictionary *attributesDictionary = [anURL resourceValuesForKeys:attributes error:nil];  //获取文件大小  NSNumber *fileSizeInBytes = [attributesDictionary objectForKey:NSURLFileSizeKey];  //获取最近修改日期  NSDate *lastModifiedDate = [attributesDictionary objectForKey:NSURLContentModificationDateKey];
  • NSFileManager列出文件夹内容时,预抓取属性

    • 节省时间

        NSArray *attributes = [NSArray arrayWithObjects:NSURLFileSizeKey,NSURLContentModificationDateKey,nil];  NSArray *folderContents = [fileManager   contentsOfDirectoryAtURL:folderURL  includingPropertiesForKeys:attributes //就是这里  options:0  error:error];
  • 创建目录
    • [fileManager createDirectoryAtURL:anURL withIntermediatetDirectories:YES attributes:nil error:nil];
    • withIntermediatetDirectories:YES创建额外需要的文件夹,创建父目录不存在的子目录,自动将父目录创建
  • 创建文件
    • [fileManager createFileAtPath:aPath contents:someData attributes:nil];
  • 删除文件
    • [fileManager removeItemAtURL:anURL error:nil];
    • 这样删除不会移至垃圾箱
  • 移动文件
    • [file moveAtURL:sourceURL toURL:destinationURL error:nil]; -> BOOL
  • 复制文件
    • [file copyItemAtURL:sourceURL toURL:destinationURL error:nil]; -> BOOL


文/扬扬扬(简书作者)
原文链接:http://www.jianshu.com/p/3355373e0b81
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

0 0
原创粉丝点击