这篇文章主要为大家详细介绍了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);
输出结果如下:
2016-03-30 14:48:02.939 沙盒机制and文件路径[11786:518929] 百度: 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];
通过简短实例为大家区分NSBundle和NSURL,希望对大家的学习有所帮助。
织梦狗教程
本文标题为:IOS UI学习教程之区分NSBundle和NSURL(读取文件、写入文件)
基础教程推荐
猜你喜欢
- Flutter绘图组件之CustomPaint使用详解 2023-05-12
- iOS开发教程之XLForm的基本使用方法 2023-05-01
- Flutter手势密码的实现示例(附demo) 2023-04-11
- android studio按钮监听的5种方法实例详解 2023-01-12
- Android多返回栈技术 2023-04-15
- IOS应用内跳转系统设置相关界面的方法 2022-11-20
- IOS 播放系统提示音使用总结(AudioToolbox) 2023-03-01
- Android中的webview监听每次URL变化实例 2023-01-23
- 解决Android Studio突然不显示logcat日志的问题 2023-02-04
- Android开发使用RecyclerView添加点击事件实例详解 2023-06-15
