• IOS开发-UI学习-NSBundle和NSURL的区别(读取文件以及写入文件)


    NSBundle和NSURL的区别:

    在项目的工程中添加一个文件,本例程添加的是aa.txt,文件的内容为百度: www.baidu.com,现在要使用NSBundle和NSURL分别去获取内容,代码如下:

     1 //    读取文件内容
     2 //    方法1:按照文件路径读取
     3     NSString *pathBundle = [[NSBundle mainBundle]pathForResource:@"aa" ofType:@"txt"];
     4     NSString *outstringbundle = [NSString stringWithContentsOfFile:pathBundle encoding:NSUTF8StringEncoding error:nil];
     5     
     6 //    方法2:按照URL读取
     7     NSURL *pathUrl = [[NSBundle mainBundle]URLForResource:@"aa" withExtension:@"txt" subdirectory:nil];
     8     NSString *outstringUrl = [NSString stringWithContentsOfURL:pathUrl encoding:NSUTF8StringEncoding error:nil];
     9     
    10     NSLog(@"%@
    ////////
    %@",outstringbundle,outstringUrl);

    输出结果如下:

    1 2016-03-30 14:48:02.939 沙盒机制and文件路径[11786:518929] 百度: www.baidu.com
    2 ////////
    3 百度: www.baidu.com

    写入文件:

    先新建一个文件:

    1 NSString *newPath = [NSString stringWithFormat:@"%@/Documents/New",NSHomeDirectory()];
    2 //    先把文件路径和文件名定义好
    3     NSString *newfile = [NSString stringWithFormat:@"%@/new.mp3",newPath];
    4 //    使用createFileAtPath创建文件
    5     [[NSFileManager defaultManager]createFileAtPath:newfile contents:nil attributes:nil];
    6     NSLog(@"%@",newPath);

    在读取并写入:

    1 //    写入文件
    2 //    1、先用data读取数据
    3     NSData *data = [[NSData alloc]initWithContentsOfFile:pathBundle];
    4     NSLog(@"%@",data);
    5     
    6 //    2、把读取的data写入沙盒文件,newfile为上面在沙盒文件中创建的mp3文件
    7     [data writeToFile:newfile atomically:YES];
  • 相关阅读:
    Vue3源码系列之触发更新的实现
    Vue3源码系列之依赖收集的实现
    Vue3源码系列之reactiveApi实现
    删除链表的倒数第n个节点
    Shared_ptr 参考实现
    linux 目录结构 比较老
    C++11 bind function
    状态机DP
    尾递归
    秒杀系统的构建(2)
  • 原文地址:https://www.cnblogs.com/jiwangbujiu/p/5337017.html
Copyright © 2020-2023  润新知