iOS基础学习

Objective-C基础学习之NSString字符串读写

2017-10-22  本文已影响13人  WenJim

1.直接读写文件中的字符

// 用来保存错误信息
NSError *error = nil;

// 读取文件内容
NSString *str = [NSString stringWithContentsOfFile:@"/Users/WJim/Desktop/Objective-CJiChuXueXi/Day7/cwj.txt" encoding:NSUTF8StringEncoding error:&error];

// 如果有错误信息
if (error) {
    NSLog(@"读取失败, 错误原因是:%@", [error localizedDescription]);
} else { // 如果没有错误信息
    NSLog(@"读取成功, 文件内容是:\n%@", str);
}
NSString *str = @"陈文";
BOOL flag = [str writeToFile:@"/Users/WJim/Desktop/Objective-CJiChuXueXi/Day7/cwj.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
if (flag == 1)
{
    NSLog(@"写入成功");
}
NSString *str1 = @"陈文";
BOOL flag = [str1 writeToFile:@"/Users/WJim/Desktop/Objective-CJiChuXueXi/Day7/cwj.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];

NSString *str2 = @"BC";
[str2 writeToFile:@"/Users/LNJ/Desktop/lnj.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];

NSString *str = [NSString stringWithContentsOfFile:@"/Users/WJim/Desktop/Objective-CJiChuXueXi/Day7/cwj.txt" encoding:NSUTF8StringEncoding error:&error];
NSLog(@"str = %@", str);

输出结果:BC

2.NSURL简介

NSURL *url = [NSURL URLWithString:@"file:///Users/WJim/Desktop/Objective-CJiChuXueXi/Day7/str.txt"];
NSURL *url = [NSURL fileURLWithPath:@"/Users/WJim/Desktop/Objective-CJiChuXueXi/Day7/str.txt"];

3.使用NSURL读写字符串

// 用来保存错误信息
NSError *error = nil;

// 创建URL路径
//    NSString *path = @"file://192.168.1.103/Users/WJim/Desktop/Objective-CJiChuXueXi/Day7/cwj.txt";

//  本机可以省略主机域名
//    NSString *path = @"file:///Users/WJim/Desktop/Objective-CJiChuXueXi/Day7/cwj.txt";
    NSURL *url = [NSURL URLWithString:path];

//  利用fileURLWithPath方法创建出来的URL默认协议头为file://
NSURL *url = [NSURL fileURLWithPath:@"/Users/WJim/Desktop/Objective-CJiChuXueXi/Day7/cwj.txt"];

// 读取文件内容
NSString *str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

// 如果有错误信息
if (error) {
    NSLog(@"读取失败, 错误原因是:%@", [error localizedDescription]);
} else { // 如果没有错误信息
    NSLog(@"读取成功, 文件内容是:\n%@", str);
}
NSString *str = @"陈文";
[str writeToURL:[NSURL URLWithString:@"/Users/WJim/Desktop/Objective-CJiChuXueXi/Day7/cwj.txt"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
上一篇 下一篇

猜你喜欢

热点阅读