本文实例为大家区分NSBundle和NSURL,具体实现内容如下
在项目的工程中添加一个文件,本例程添加的是aa.txt,文件的内容为百度: www.baidu.com,现在要使用NSBundle和NSURL分别去获取内容,代码如下:
?
|
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];
|
相关文章
猜你喜欢
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-29 86
-
2025-05-27 59
-
2025-06-04 106
-
2025-05-24 107
-
2025-05-29 19
热门评论

