您的位置:首页 > 其它

111,文件的读写(二)

2015-12-19 20:40 357 查看
#import <Foundation/Foundation.h>

/*

1,什么是URL

>URL的全称是Uniform Resource Locator(统一资源定位符)

>URL的互联网上的标准资源的地址

>互联网上的每个资源都有一个唯一的URL,它用于表示资源的位置

>根据一个URL就能找到唯一的一个资源

2,URL的格式

>基本URL包含协议,主机域名(服务器名称\IP地址),路径

eg:http://www.baidu.com/ios/images/pic.jpg

简单认为:URL=协议头://主机域名/路径

3,常见的URL协议头(URL类型)

>http://或https://:超文本传输协议资源,网络资源

>ftp://文件传输协议

>file://本地电脑的文件

4,URL的创建

>传入完整的字符串创建

NSURL *url = [NSURL URLWithString:@"file:///Users/JS/Desktop/test.txt "];

>通过文件路径创建(默认就是file协议的)

NSURL *url = [NSURL fileURLWithPath:@"/Users/JS/Desktop/test.txt "];

*/

int main(int argc,const
char * argv[]) {

//1,读取文件,使用URL:协议头+主机地址/IP+路径

//如果是加载本机的资源,URL中的主机地址/IP可以省略,但文件路径前面的/不能省略

//NSString *path = @"file://localhost/Users/JS/Desktop/test.txt";

//NSString *path = @"file:///Users/JS/Desktop/test.txt";

//NSString *path = @"http://www.baidu.com";

//若路径中有中文,那么,必须这么编写代码

//第一种:必须对字符串中的中文进行百分号编程

//NSString *path = @"file:///Users/JS/Desktop/测试.txt";

//path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

//NSURL *url = [NSURL URLWithString:path];

//第二种:通过NSURL的fileURLWithPath方法创建URL,那么,系统会自动给我们传入的字符串添加协议头,所以,字符串中不需要再写file://。另外,fileURLWithPath方法已经对字符串进行百分号编程处理了

NSString *path =@"/Users/JS/Desktop/测试.txt";

NSURL *url = [NSURLfileURLWithPath:path];

NSError *error =
nil;

NSString *str = [NSStringstringWithContentsOfURL:url
encoding:NSUTF8StringEncodingerror:&error];

if (error == nil) {

NSLog(@"str = %@",str);

}else{

NSLog(@"error = %@",[errorlocalizedDescription]);

}

//2,写入文件

//如果多次向同一个文件写入,那么,后面写入的内容会覆盖前面的内容

NSString *str1 =@"I'm a super man!";

NSString *path1 =@"/Users/JS/Desktop/tet.txt";

NSURL *url1 = [NSURLfileURLWithPath:path1];

BOOL flag = [str1writeToURL:url1
atomically:YESencoding:NSUTF8StringEncodingerror:nil];

if (flag) {

NSLog(@"写入文件成功!");

}

else

{

NSLog(@"写入文件失败!");

}

return 0;

}

//2015-12-19 20:42:16.827 6,文件读写[2686:184205] error = The file “测试.txt” couldn’t be opened because there is no such file.

//2015-12-19 20:42:16.830 6,文件读写[2686:184205]写入文件成功!

//Program ended with exit code: 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: