IOS之文件的写入和读出

// 获取文件路径
   /**  1
     *  bundle是一个目录,其中包含应用程序的所有资源,通过mainBundle 得到这个目录后就可以获取resource下的资源
     */
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"ContactsInfo" ofType:nil];
    NSLog(@"%@", filePath);
    // 将文件中的内容取出来 存储成字符串 有了其中的内容就可以做一些相应的操作了
    NSString *string = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@", string);
    
    //获取沙盒路径  得到这个路径就可以找到其中的问件
    NSString *sandboxPath = NSHomeDirectory();
    NSLog(@"%@", sandboxPath);
    /**
     *  沙盒中共有3个文件夹
     * 1 Documents 将程序中建立的或在程序中浏览到的文件数据保存在该目录下
     * 2 Library 存储程序的默认设置或其他状态信息
     * 3 tmp     存放临时文件
     * 4 应用程序包
     */
    // 获取Document路径
    // 方法 1
    NSString *documentFilePath = [sandboxPath stringByAppendingString:@"/Document"];
    NSLog(@"%@", documentFilePath);
    // 方法 2
    NSString *documentFilePath1 = [sandboxPath stringByAppendingPathComponent:@"Doucment"];
    NSLog(@"%@", documentFilePath1);
    // 方法 3
    NSString *documentFilePath2 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSLog(@"%@", documentFilePath2);
    
    // 这三种方法都能取得 Document
    
    // 将字符串写入指定文件 第二次写入会覆盖第一次写入的内容
    NSString *aFilePath = [documentFilePath2 stringByAppendingString:@"a.txt"];
    NSString *str = @"hello world";
    [str writeToFile:aFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    // 读出指定文件中的字符串
    NSString *str2 = [NSString stringWithContentsOfFile:aFilePath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@", str2);
    /**
     *  文件的写入和读出是有条件的 NSString NSArray NSDictionary NSData 这几种类型的数据才可以写入
     *
     *   NSArray NSDictionary NSData 的写入和读出方法大同小异
     */

仅供参考 大神勿喷

转载于:https://www.cnblogs.com/NatureZhang/p/3700060.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值