• 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 的写入和读出方法大同小异
         */

    仅供参考 大神勿喷

  • 相关阅读:
    github分支规范
    前端工程师为什么要学习编译原理?
    现代编译原理——第六章:中间树 IR Tree 含源码
    现代编译原理——第五章:活动记录
    现代编译原理——第四章:语义分析以及源码
    现代编译原理——第三章:抽象语法树以及源码
    现代编译原理——第二章:语法分析之LL(K)
    现代编译原理——第1章:词法分析
    现代编译原理——第0章
    优雅的数组降维——Javascript中apply方法的妙用
  • 原文地址:https://www.cnblogs.com/NatureZhang/p/3700060.html
Copyright © 2020-2023  润新知