字符串读写

本小节知识点:

  1. 【掌握】直接读写文件中的字符
  2. 【了解】NSURL简介
  3. 【掌握】使用NSURL读写字符串

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

  • 从文件中读取
// 用来保存错误信息
NSError *error = nil;

// 读取文件内容
NSString *str = [NSString stringWithContentsOfFile:@"/Users/cdh/Desktop/cdh.txt" encoding:NSUTF8StringEncoding error:&error];

// 如果有错误信息
if (error) {
    NSLog(@"读取失败, 错误原因是:%@", [error localizedDescription]);
} else { // 如果没有错误信息
    NSLog(@"读取成功, 文件内容是:\n%@", str);
}
  • 写入文件中
NSString *str = @"豪哥";
BOOL flag = [str writeToFile:@"/Users/cdh/Desktop/cdh.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
if (flag == 1)
{
    NSLog(@"写入成功");
}
  • 重复写入同一文件会覆盖掉上一次的内容
NSString *str1 = @"豪哥";
BOOL flag = [str1 writeToFile:@"/Users/cdh/Desktop/cdh.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];

NSString *str2 = @"德豪";
[str2 writeToFile:@"/Users/cdh/Desktop/cdh.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];

NSString *str = [NSString stringWithContentsOfFile:@"/Users/cdh/Desktop/cdh.txt" encoding:NSUTF8StringEncoding error:&error];
NSLog(@"str = %@", str);

输出结果:德豪

2.NSURL简介

  • 什么是URL

    • URL的全称是Uniform Resource Locator(统一资源定位符)
    • URL是互联网上标准资源的地址
    • 互联网上的每个资源都有一个唯一的URL,它包含的信息指出资源的位置
    • 根据一个URL就能找到唯一的一个资源
  • URL的格式

  • 常见的URL协议头(URL类型)

    • http://\https:// :超文本传输协议资源, 网络资源
    • ftp:// :文件传输协议
    • file:// :本地电脑的文件
  • URL的创建

    • 传入完整的字符串创建
      NSURL *url = [NSURL URLWithString:@"file:///Users/cdh/Desktop/str.txt"];
      
    • 通过文件路径创建(默认就是file协议的)
      NSURL *url = [NSURL fileURLWithPath:@"/Users/cdh/Desktop/str.txt"];
      

3.使用NSURL读写字符串

  • 从URL中读取
// 用来保存错误信息
NSError *error = nil;

// 创建URL路径
//    NSString *path = @"file://192.168.199.119/Users/cdh/Desktop/cdh.txt";

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

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

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

// 如果有错误信息
if (error) {
    NSLog(@"读取失败, 错误原因是:%@", [error localizedDescription]);
} else { // 如果没有错误信息
    NSLog(@"读取成功, 文件内容是:\n%@", str);
}
  • 写入URL中
NSString *str = @"豪哥";
[str writeToURL:[NSURL URLWithString:@"/Users/cdh/Desktop/cdh.txt"] atomically:YES encoding:NSUTF8StringEncoding error:nil];

results matching ""

    No results matching ""