zoukankan      html  css  js  c++  java
  • IOS开发中判断文件是否存在,不存在则拷贝

    首先,先总结一下如何获取Documents目录,在ios开发中,我们经常需要检索Documents目录的完整路径以便读取和写入文件,我总结了以下两种方法:

    1、NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

    2、NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    

    NSString *documentsDirectory = [paths objectAtIndex:0];

     以上documentsDirectory就是获取的Documents的完整路径。

     程序的所有资源文件,存储在程序包中,获取程序包路径的方法是:

    NSString *appDirectory = [[NSBundle mainBundle] bundlePath];

    在实际开发中我们有时需要判断Documents下的某个资源文件是否存在,如果不存在,则从程序包中拷贝进去,现在假设要判定的文件是"xxx.txt",判定代码如下:

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *filePath = [self [documentsDirectory stringByAppendingPathComponent:@"xxx.txt"]];

    if(![fileManager fileExistsAtPath:filePath]) //如果不存在

    {      

      NSLog(@"xxx.txt is not exist");    

       NSString *dataPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/xxx.txt"];//获取程序包中相应文件的路径      

      NSError *error;    

       if([fileManager copyItemAtPath:dataPath toPath:filePath error:&error]) //拷贝      

      {           

        NSLog(@"copy xxx.txt success");      

      }    

       else       

      {           

        NSLog(@"%@",error);      

      }  

    }

  • 相关阅读:
    GCD 使用说明
    iOS操作系统的层次结构
    Objective-C 类型转换
    UIView和Masonry实现动画效果
    iOS 常用手势
    SDUT 2610 Boring Counting(离散化+主席树区间内的区间求和)
    HDU 4417 Super Mario(主席树求区间内的区间查询+离散化)
    NBUT 1525 Cow Xor(01字典树+前缀思想)
    HDU 4825 Xor Sum(经典01字典树+贪心)
    HDU 1069 Monkey and Banana(二维偏序LIS的应用)
  • 原文地址:https://www.cnblogs.com/tianguook/p/3054048.html
Copyright © 2011-2022 走看看