通过NSString读写文件(File)
//路径
NSString *path=@"/Users/RHP/Desktop/练习/01-OC增强/20141221/08-通过NSString读写文件/2.txt";
NSString *msg=@"我现在听的歌曲是:邓丽君的《往事只能回味》";
//错误信息 使用的时候要加上&err 因为它是指向指针的指针
NSError *err=nil;
BOOL isok=[msg writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&err];
if (isok) {
NSLog(@"写入成功");
}
else
{
NSLog(@"写入失败");
NSLog(@"错误信息是%@",[err localizedDescription]);
}
//2>==================== 读取文件 stringWithContentsOfFile ===================
NSString *path1=@"/Users/RHP/Desktop/练习/01-OC增强/20141221/08-通过NSString读写文件/2.txt";
NSError *err1=nil;
//读取出来的文件信息
NSString *msg1=[NSString stringWithContentsOfFile:path1 encoding:NSUTF8StringEncoding error:&err1];
if (err1==nil) {
NSLog(@"读取成功");
NSLog(@"%@",msg1);
}
else{
NSLog(@"读取失败");
NSLog(@"错误信息是:%@",[err1 localizedDescription]);
}
通过NSString读写文件(NSURL)
//1>========= 通过NSURL写入文件 writeToURL =========
/*
//路径
NSString *path=@"file:///Users/RHP/Desktop/练习/01-OC增强/20141221/08-通过NSString读写文件/08-通过NSString读写文件/4.txt";
//创建一个URL对象
NSURL *url=[NSURL URLWithString:path];
**注意**:这种方式不能识别中文,并且路径前面要加上协议头file://
*/
//路径
NSString *path=@"/Users/RHP/Desktop/练习/01-OC增强/20141221/08-通过NSString读写文件/08-通过NSString读写文件/4.txt";
//创建一个URL对象
NSURL *url=[NSURL fileURLWithPath:path];
//创建要写入的字符串
NSString * msg=@"前几天我一直在听好妹妹乐队的我到外地去看你";
NSError *err=nil;
//将字符串写入到文件
BOOL isok=[msg writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&err];
if (isok) {
NSLog(@"写入成功");
}
else{
NSLog(@"写入失败");
NSLog(@"错误的详细信息是;%@",[err localizedDescription]);
}
//2>== 通过NSURL读取文件 stringWithContentsOfURL ==
NSString *path1=@"/Users/RHP/Desktop/练习/01-OC增强/20141221/08-通过NSString读写文件/08-通过NSString读写文件/4.txt";
NSURL *url1=[NSURL fileURLWithPath:path1];
NSError *err1=nil;
NSString *msg1=[NSString stringWithContentsOfURL:url1 encoding:NSUTF8StringEncoding error:&err1 ];
if (err1==nil) {
NSLog(@"读取成功");
NSLog(@"%@",msg1);
}
else
{
NSLog(@"读取失败");
NSLog(@"错误信息为:%@",[err1 localizedDescription]);
}
}