zoukankan      html  css  js  c++  java
  • [ios]ios读写文件本地数据

    参考:http://blog.csdn.net/tianyitianyi1/article/details/7713103

    ios - Write写入方式:永久保存在磁盘中。具体方法为:
    第一步:获得文件即将保存的路径:

    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

    //使用C函数NSSearchPathForDirectoriesInDomains来获得沙盒中目录的全路径。该函数有三个参数,目录类型、he domain mask、布尔值。其中布尔值表示是否需要通过~扩展路径。而且第一个参数是不变的,即为NSSearchPathDirectory 。在IOS中后两个参数也是不变的,即为:NSUserDomainMask 和 YES。
    NSString *ourDocumentPath =[documentPaths objectAtIndex:0];

    还有一种方法是使用NSHomeDirectory函数获得sandbox的路径。具体的用法为:

    NSString *sandboxPath = NSHomeDirectory();
    // Once you have the full sandbox path, you can create a path from it,但是不能在sandbox的本文件层上写文件也不能创建目录,而应该是此基础上创建一个新的可写的目录,例如Documents,Library或者temp。
    NSString *documentPath = [sandboxPath
    stringByAppendingPathComponent:@"Documents"];//将Documents添加到sandbox路径上,具体原因前面分析了!
    这两者的区别就是:使用NSSearchPathForDirectoriesInDomains比在NSHomeDirectory后面添加Document更加安全。因为该文件目录可能在未来发送的系统上发生改变。

    第二步:生成在该路径下的文件:
    NSString *FileName=[documentDirectory stringByAppendingPathComponent:fileName];//fileName就是保存文件的文件名
    第三步:往文件中写入数据:
    [data writeToFile:FileName atomically:YES];//将NSData类型对象data写入文件,文件名为FileName

    最后:从文件中读出数据:

    NSData data=[NSData dataWithContentsOfFile:FileName options:0 error:NULL];//从FileName中读取出数据

    ios如何加载本地文件

    参考:http://zhidao.baidu.com/link?url=X8OwqyYTOXTu01x8j55grEVp5XxNjM57h3tVJizRL9zVNgJGXii0K9kqdlnCDpBvobNHaTye30W2mLlp3yVhAAcisetZVCckGuzCk7juA8a
    1,本地的html文件一定要放到工程文件的根目录

    2,html代码中的图片路径一定要是相对路径

    3,下面是用UIWebView调用本地文件的方法

    方法一:

    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"1" ofType:@"html"];

    NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]

    [myWebView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]];

    方法二:

    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"1" ofType:@"html"];

    NSURL *url = [NSURL fileURLWithPath:filePath];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    [myWebView loadRequest:request];

    [self.view addSubview:myWebView];
  • 相关阅读:
    python中使用schedule模块定时执行任务
    python marshmallow库
    shell 脚本根据名称查找进程id会多出来两个id号
    docker随笔(1)
    python实现-kafka作为消息中间件 -实现数据生产和消费-实用的脚本
    python-kafka文档
    mysql文档
    VMware pro15安装centos7
    excel表计算和计算器计算结果不一致
    jmeter安装部署、maven路径配置
  • 原文地址:https://www.cnblogs.com/lyggqm/p/4551531.html
Copyright © 2011-2022 走看看