当前位置: 移动技术网 > 移动技术>移动开发>IOS > IOS UI学习教程之区分NSBundle和NSURL(读取文件、写入文件)

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

2019年07月24日  | 移动技术网移动技术  | 我要评论

本文实例为大家区分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,希望对大家的学习有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网