zoukankan      html  css  js  c++  java
  • 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 的写入和读出方法大同小异
         */

    仅供参考 大神勿喷

  • 相关阅读:
    【资源共享】JNI 课题
    Firefly自动售货机解决方案
    【资源共享】Android开发技巧整理
    【资源共享】《Rockchip IO-Domain 开发指南 V1.0》
    【人脸识别+硬件】Firefly推出可商业化的人脸识别方案
    【技术案例】双目摄像头数据采集
    windows环境常用网络命令测试和分析(51cto实验01~02)
    利用三层交换机实现VLAN间路由配置
    c++11
    归并排序
  • 原文地址:https://www.cnblogs.com/NatureZhang/p/3700060.html
Copyright © 2011-2022 走看看