zoukankan      html  css  js  c++  java
  • 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];
  • 相关阅读:
    vc 获得文件相对路径
    C#关闭MessageBox消息框(转)
    ip地址及地理位置查询
    WinDbg关联dump文件
    国外程序员推荐:每个程序员都应读的书
    [转]史上最全的C位域总结201036 2:58:00
    android 屏幕保持唤醒 不锁屏
    [转]win7如何共享
    一些DirectUI方面的资料
    计算器程序,可以计算正实数范围内的任何数据的加减乘除括号,混合运算
  • 原文地址:https://www.cnblogs.com/jiwangbujiu/p/5337017.html
Copyright © 2011-2022 走看看