读写txt/rtf文件

2017-03-10  本文已影响686人  PZcoder

目录:
1、txt文件写入
2、txt文件读取
3、rtf文件读取
4、NSString转换成其他类型数据方法

1、txt文件写入

//获取文件路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *newPath= [documentsDirectory stringByAppendingPathComponent:@"newFile.txt"];
    
    //要写入txt文件的内容
    NSString *fileContent = @"Write to file...";
//写入文件方法1.使用文件管理的方式写入内容
    NSFileManager *fileManager = [[NSFileManager alloc]init];
    NSData *fileData = [fileContent dataUsingEncoding:NSUTF8StringEncoding];
    [fileManager createFileAtPath:newPath contents:fileData attributes:nil];
//写入文件方法2.直接写入字符串内容
[arr writeToFile:pathStr atomically:YES];
    NSError *error = nil;//数组写入方法
    
    [fileContent writeToFile:newPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    
    if (!error)
    {
        NSLog(@"字符串写入成功!");
    }
    else
    {
        NSLog(@"字符串写入失败,原因是:%@",[error localizedDescription]);
    }

2、txt文件读取

//读取txt文件内容
    NSString *str = [NSString stringWithContentsOfFile:newPath encoding:NSUTF8StringEncoding error:&error];

    if (!error)
    {
        NSLog(@"txt内容为:%@",str);
    }
    else
    {
        NSLog(@"文件读取失败,原因是:%@",[error localizedDescription]);
    }

3、rtf文件读取

rtf文件不能像txt文件一样直接读取文件内容,
在此我的方法是把rtf内容转换成txt之后再读取:

转换方式1、如有虚拟机装有Windows系统则直接创建txt文件,复制内容即可。但是此时需要注意,读取此txt文件时会报错:The file “NewData.txt” couldn’t be opened using text encoding Unicode (UTF-8).需要特殊处理如下:

    if (error)  //解析错误时打印错误信息
    {
        //error == The file “NewData.txt” couldn’t be opened using text encoding Unicode (UTF-8).
        NSLog(@"error == %@",[error localizedDescription]);
        
        if (!str)   //解析错误时按GBK编码再解码一次
        {
            str = [NSString stringWithContentsOfFile:newPath encoding:0x80000632 error:nil];
        }
    }

转换方式2、没有Windows虚拟机时,需要自己用代码创建一个txt文件(其他方式不会),方法如前所述,创建txt文档后复制rtf文件内容即可,此时不用做特殊处理即可读取文件内容。

至于直接改文件名字的方式会出现乱码的情况

4、NSString转换成其他类型数据方法

在获取到文件内容的字符串之后,有时需要把字符串格式转换成想要的格式,可以通过NSData过渡一下,进行转换。

//NSString转换其他数据类型  //首先转换成NSData类型
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    //NSData类型转换成字典 //数组、字典、字符串等接收即可
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
上一篇 下一篇

猜你喜欢

热点阅读