• Object-c:两种文件读写的对比


    一、读写方法对比:(主要针对本地读取本地文件)
    方式操作
    非URL方式

    stringWithContentsOfFile

    writeToFile

    URL方式

    stringWithContentsOfURL

    writeToURL

    实际开发中,大部分都采用URL方式。
    对于写入操作,情况都是:如果文件存在,则覆盖原文件中的内容;如果文件不存在,则创建一个新文件
     
    二、非URL方式
    1.比较陌生的是文件写入的方法中,会有个atomically参数。
       atomically(原子性):设置YES时,没有写完,则会全部撤销(比较安全的做法)。
                                             设置NO时,没有写完,不会撤销。
    2.NSError对象,可以通过localizedDescription方法获取报错信息。
     
     
    例子:
    //
    //  main.m
    //  字符串练习2:读写文件
    //
    //  Created by Apple on 15/12/7.
    //  Copyright © 2015年 Apple. All rights reserved.
    //
    #import <Foundation/Foundation.h>
    void readFile(NSString *path);
    void writeToFile(NSString *path, NSString *str);
    
    int main(int argc, const char * argv[]) {
        //读取文件中的内容
        //NSString *path1 = @"/Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/字符串练习2:读写文件/1.txt";
        NSString *path1 = @"/Users/apple/Desktop/1.txt";
        NSLog(@"读取文件:");
        readFile(path1);
    
        //写入文件内容
        NSString *path2 = @"/Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/字符串练习2:读写文件/2.txt";
        NSLog(@"写入文件");
        NSString *str = @"这是一个测试";
        writeToFile(path2,str);
    
        NSLog(@"读取文件:");
        readFile(path2);
    
        return 0;
    }
    
     
    
    //读取文件
    void readFile(NSString *path){
        NSError *error = nil;
        NSString *str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
        if (error != nil) {
            NSLog([error localizedDescription]);//将错误信息输出来
        }
        else{
            NSLog(@"%@",str);
        }
    }
    //写入文件
    void writeToFile(NSString *path, NSString *str){
        NSError *error = nil;
        //atomically : YES时,没有写完,则会全部撤销;NO时候,没有写完,不会撤销
        //注意:这种写入方式,如果文件补存在,则创建;如果文件存在,则覆盖原文件的内容
        BOOL flag = [str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];//一般error都设置为nil,保证写入成功
        if (flag) {
            NSLog(@"写入成功");
        }
        else{
            NSLog(@"写入失败");
        }
    }
     
    三、URL方式
    URL方式,根据URL对象的创建方式,又分为两种:
    一.通过URLWithString方法创建URL对象
    1)路径:协议 + ip + 文件路径
    访问本地资源:file:// + ip + /文件路径
    访问网络资源:http:// + ip + /文件路径
    注意:(1)读取本地资源的时候,ip地址可以省略,即:file:///文件路径(ip地址后面/不能省略,代表着根路径)
            (2)路径中如果包含中文的时候,需要使用stringByAddingPercentEscapesUsingEncoding方法或stringByAddingPercentEncodingWithAllowedCharacters方法进行路径进行编码,不然,会提示:The file couldn’t be opened because the specified URL type isn’t supported.(URL类型不支持)
     
    例如:
    NSString *path = @"file://192.168.1.103/Users/apple/Desktop/读写文件练习2/1.txt”;
    //NSString *path = @"file:///Users/apple/Desktop/读写文件练习2/1.txt”;
    //path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//比较老的方法,现在被下面的方法取代
    path = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSURL *url = [NSURL URLWithString:path];
    
    NSString *str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
    
    if (error == nil) {
        NSLog(@"%@",str);
    }
    else{
            NSLog(@"%@",[error localizedDescription]);
    } 
     
    二.通过fileURLWithPath方法创建URL对象,访问本地资源

    使用这个方法时,需要注意:

         1)系统会帮我们自动加入file://,我们不需要再添加。再添加,路径就不对了。

         2)即使URL中包含中文,都可以访问。系统会自动对包含的中文进行处理。所以一般开发中,访问本地资源,都使用这个方法。

     
    例子:
    NSString *path = @"/Users/apple/Desktop/读写文件练习2/1.txt”;
     
    NSURL *url = [NSURL fileURLWithPath:path];
    
    NSString *str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
    
    if (error == nil) {
        NSLog(@"%@",str);
    }
    else{
        NSLog(@"%@",[error localizedDescription]);
    }
     
    三、综合例子:
    //
    //  main.m
    //  读写文件练习2
    //
    //  Created by Apple on 15/12/7.
    //  Copyright © 2015年 Apple. All rights reserved.
    //
    
    #import <Foundation/Foundation.h>
    
    int main(int argc, const char * argv[]) {
        //一.文件读取
        //路径使用URL
        //1.加载本地文件。注意:file://,不是file:///
        NSString *path = @"file://192.168.1.103/Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/读写文件练习2/1.txt";
    
        //如果加载的是本地资源,那么URL上的主机地址可以不要
        //注意:ip地址后面的斜杠不能省略!(其代表着跟路径)
        //path = @"file:///Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/读写文件练习2/1.txt";
    
        //如果路径中包含中文,先进行编码
        //不编码的后果是:The file couldn’t be opened because the specified URL type isn’t supported.(URL类型不支持)
        //path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//比较老的方法,现在被下面的方法取代
        //path = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
        //2.加载网络资源
        //path = @"http://www.baidu.com";
    
        //NSURL *url = [NSURL URLWithString:path];
    
        //3.使用fileURLWithPath创建URL对象,加载本地资源。
        /*
         使用这个方法时,需要注意:
         1)系统会帮我们自动加入file://,我们不需要再添加。再添加,路径就不对了。
         2)即使URL中包含中文,都可以访问。系统会自动对包含的中文进行处理。所以一般开发中,访问本地资源,都使用这个方法。
         */
        path = @"/Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/读写文件练习2/1.txt";
        NSURL *url = [NSURL fileURLWithPath:path];
    
        NSError *error = nil;
        
        NSString *str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
        if (error == nil) {
            NSLog(@"%@",str);
        }
        else{
            NSLog(@"%@",[error localizedDescription]);
        }
    
    
        //二.文件写入
        //路径使用URL
        NSError *error2 = nil;
        NSString *str2 = @"this is a test2";
    
        /*
        //第一种方式
        NSString *path2 =@"file:///Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/读写文件练习2/2.txt";
        path2 = [path2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"path2 = %@",path2);
        NSURL *url2 = [NSURL URLWithString:path2];
        */
    
        //第二种方式
        NSString *path2 = @"/Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/读写文件练习2/2.txt";
        NSURL *url2 = [NSURL fileURLWithPath:path2];
    
        //注意:如果文件存在,则覆盖原文件的内容;如果文件不存在,则新建
        [str2 writeToURL:url2 atomically:YES encoding:NSUTF8StringEncoding error:&error2];
        if (error2 != nil) {
            NSLog(@"%@", [error2 localizedDescription]);
        }
        else{
            NSLog(@"文件写入成功!");
        }
    
        return 0;
    }
     
    推荐阅读:
     
     
     
     
     
     
  • 相关阅读:
    SpringBoot通过注解获取接口信息
    2.2.0Nginx代理与负载均衡
    1.1Nginx概述
    Nginx安装整合
    每日日报27
    PHP所遇问题——注意:未定义的索引
    每日日报26
    每日日报25
    每日日报24
    每日日报23
  • 原文地址:https://www.cnblogs.com/KeenLeung/p/5028012.html
Copyright © 2020-2023  润新知