·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> IOS UI学习教程之区分NSBundle和NSURL(读取文件、写入文件)

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

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

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