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

时间:2023-03-08 20:51:25
IOS开发-UI学习-NSBundle和NSURL的区别(读取文件以及写入文件)

NSBundle和NSURL的区别:

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

 //    读取文件内容
// 方法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);

输出结果如下:

 -- ::02.939 沙盒机制and文件路径[:] 百度: www.baidu.com
////////
百度: www.baidu.com

写入文件:

先新建一个文件:

 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、先用data读取数据
NSData *data = [[NSData alloc]initWithContentsOfFile:pathBundle];
NSLog(@"%@",data); // 2、把读取的data写入沙盒文件,newfile为上面在沙盒文件中创建的mp3文件
[data writeToFile:newfile atomically:YES];