IOS开发中判断文件是否存在,不存在则拷贝

[objc]  view plain  copy
  1.     首先,先总结一下如何获取Documents目录,在ios开发中,我们经常需要检索Documents目录的完整路径以便读取和写入文件,我总结了以下两种方法:  
  2. 1NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];  
  3. 2NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
  4.    NSString *documentsDirectory = [paths objectAtIndex:0];  
  5.  以上documentsDirectory就是获取的Documents的完整路径。  
  6.  程序的所有资源文件,存储在程序包中,获取程序包路径的方法是:  
  7. NSString *appDirectory = [[NSBundle mainBundle] bundlePath];  
  8. 在实际开发中我们有时需要判断Documents下的某个资源文件是否存在,如果不存在,则从程序包中拷贝进去,现在假设要判定的文件是"xxx.txt",判定代码如下:  
  9. NSFileManager *fileManager = [NSFileManager defaultManager];  
  10. NSString *filePath = [self [documentsDirectory stringByAppendingPathComponent:@"xxx.txt"]];  
  11. if(![fileManager fileExistsAtPath:filePath]) //如果不存在  
  12. {  
  13.      NSLog(@"xxx.txt is not exist");  
  14.      NSString *dataPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/xxx.txt"];//获取程序包中相应文件的路径  
  15.      NSError *error;  
  16.      if([fileManager copyItemAtPath:dataPath toPath:filePath error:&error]) //拷贝  
  17.      {  
  18.           NSLog(@"copy xxx.txt success");  
  19.      }  
  20.      else   
  21.      {  
  22.           NSLog(@"%@",error);  
  23.      }    
  24. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值