IOS UI学习教程之区分NSBundle和NSURL(读取文件、写入文件)

2025-05-29 0 69

本文实例为大家区分NSBundleNSURL,具体实现内容如下

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

?

1

2

3

4

5

6

7

8

9

10
// 读取文件内容

// 方法1:按照文件路径读取

NSString *pathBundle = [[NSBundle mainBundle]pathForResource:@"aa" ofType:@"txt"];

NSString *outstringbundle = [NSString stringWithContentsOfFile:pathBundle encoding:NSUTF8StringEncoding error:nil];

// 方法2:按照URL读取

NSURL *pathUrl = [[NSBundle mainBundle]URLForResource:@"aa" withExtension:@"txt" subdirectory:nil];

NSString *outstringUrl = [NSString stringWithContentsOfURL:pathUrl encoding:NSUTF8StringEncoding error:nil];

NSLog(@"%@\\n////////\\n%@",outstringbundle,outstringUrl);

输出结果如下:

?

1

2

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

////////

百度: www.baidu.com

写入文件:

先新建一个文件:

?

1

2

3

4

5

6
NSString *newPath = [NSString stringWithFormat:@"%@/Documents/New",NSHomeDirectory()];

// 先把文件路径和文件名定义好

NSString *newfile = [NSString stringWithFormat:@"%@/new.mp3",newPath];

// 使用createFileAtPath创建文件

[[NSFileManager defaultManager]createFileAtPath:newfile contents:nil attributes:nil];

NSLog(@"%@",newPath);

在读取并写入:

?

1

2

3

4

5

6

7
// 写入文件

// 1、先用data读取数据

NSData *data = [[NSData alloc]initWithContentsOfFile:pathBundle];

NSLog(@"%@",data);

// 2、把读取的data写入沙盒文件,newfile为上面在沙盒文件中创建的mp3文件

[data writeToFile:newfile atomically:YES];

通过简短实例为大家区分NSBundleNSURL,希望对大家的学习有所帮助。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 IOS UI学习教程之区分NSBundle和NSURL(读取文件、写入文件) https://www.kuaiidc.com/93184.html

相关文章

发表评论
暂无评论