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];
  • 相关阅读:
    (转)【web前端培训之前后端的配合(中)】继续昨日的故事
    ural(Timus) 1136. Parliament
    scau Josephus Problem
    ACMICPC Live Archive 6204 Poker End Games
    uva 10391 Compound Words
    ACMICPC Live Archive 3222 Joke with Turtles
    uva 10132 File Fragmentation
    uva 270 Lining Up
    【转】各种字符串哈希函数比较
    uva 10905 Children's Game
  • 原文地址:https://www.cnblogs.com/jiwangbujiu/p/5337017.html
Copyright © 2011-2022 走看看