NSFileManager & NSFileHandle操作

/** 此处使用NSCachesDirectory App中的缓存文件夹作为案例 */

NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

 NSString *cachePath = [pathArray firstObject];


 //在cache文件夹下新建一个GTData文件夹

 NSString *dataPath = [cachePath stringByAppendingPathComponent:@"GTData"];

 NSFileManager *fileManager = [NSFileManager defaultManager];

 NSError *createError;

 [fileManager createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&createError];


 //创建文件

 NSString *listDataPath = [dataPath stringByAppendingPathComponent:@"list"];

 NSData *listData = [@"abc" dataUsingEncoding:NSUTF8StringEncoding];

 [fileManager createFileAtPath:listDataPath contents:listData attributes:nil];


 //查询文件是否存在

 BOOL fileExist = [fileManager fileExistsAtPath:listDataPath];


 //删除文件

    if (fileExist) {

 [fileManager removeItemAtPath:listDataPath error:nil];

    }


 NSFileHandle *fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:listDataPath];

 [fileHandler seekToEndOfFile];

 [fileHandler writeData:[@"def" dataUsingEncoding:NSUTF8StringEncoding]];

 //刷新文件中的数据

 [fileHandler synchronizeFile];

 //关闭文件操作(若不主动关闭,在销毁FileHandle时系统也会自动关闭)

 [fileHandler closeFile];

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • iOS开发-文件管理(一) 一、iOS中的沙盒机制 iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭...
    Friez平板支撑阅读 4,658评论 0 1
  • 一、iOS中的沙盒机制 iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭、安全的空间,叫做沙盒。它一...
    1d5cb7cff98d阅读 1,801评论 0 0
  • iOS开发系列--网络开发 概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博、微信等,这些应用本身可...
    lichengjin阅读 3,773评论 2 7
  • 27、ViewController的didReceiveMemoryWarning是在什么时候调用的?默认的操作是...
    烟雨平生花飞舞阅读 647评论 0 1
  • 这几天,只画成了一个头像,也没拍过程。显得太单薄,就没传上来。昨晚半夜倒是爬起来画了两小时,两次都以失败告终。别误...
    尧光gxl阅读 574评论 15 13