• Object-c学习之路六(oc字符串文件读写)


    //
    //  main.m
    //  NSString
    //
    //  Created by WildCat on 13-7-25.
    //  Copyright (c) 2013年 wildcat. All rights reserved.
    //
    
    #import <Foundation/Foundation.h>
    
    void testCreat(){
        NSString *str=@"你好。";
        NSLog(@"str :%@",str);
        
        NSString *str2=[NSString stringWithUTF8String:"哈哈哈"];
        NSLog(@"str2 :%@",str2);
        NSString *str3=[[NSString alloc] initWithString:@"测试3"] ;
        NSLog(@"str3 :%@",str3);
    
    }
    #pragma mark 从文件中获取
    void creatWithContent(){
    
       //设置gb2312编码格式: CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        
        NSError *error;
        
        NSString *str=[NSString stringWithContentsOfFile:@"/Users/bird/Desktop/资料/qqq.txt" encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000) error:&error];
        if (error==nil){//如果不为空,说明读去正常
            NSLog(@"文档中获取:%@",str);
        }else{
           NSLog(@"出现错误:%@",error);
        }
        
        //用url读取文件内容:
        NSError *error2;
        NSURL *url=[NSURL URLWithString:@"file:///Users/bird/Downloads/qqq.txt"];
        NSString *str2=[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error2];
        
            NSLog(@"文档中获取2:%@",str2);
        //获得远程的文件
        NSURL *url3=[NSURL URLWithString:@"http://www.baidu.com"];
        NSString *str3=[NSString stringWithContentsOfURL:url3 encoding:NSUTF8StringEncoding error:nil];
        
        NSLog(@"文档中获取3:%@",str3);
        
    }
    
    #pragma mark 写入文件
    void writeToFile(){
        //要写入的字符串
        NSString *str3=@"你好吗?";
    
        NSError *error;
        //写入文件   YES 代表原子性操作  ,也就是会创建一个中间的临时文件
        [str3 writeToFile:@"/Users/bird/Downloads/qqq.txt" atomically:YES encoding:NSUTF8StringEncoding error:&error];
        
        if (error){
            //[error localizedDescription]  会打印出主要的错误信息
            NSLog(@"写入失败:%@",[error localizedDescription]);
        
        }else{
            NSLog(@"写入成功");
        }
    
    
    }
    
    #pragma mark 主函数
    int main(int argc, const char * argv[])
    {
    
        @autoreleasepool {
            
           // testCreat();
           // creatWithContent();
            writeToFile();
        }
        return 0;
    }
    


  • 相关阅读:
    mogodb学习
    rman list incarnation
    Java创建对象的四种方式
    JAVA 8 函数式接口--Consumer
    Linux中VIM的使用
    JRE 和 JDK 的区别
    tengine-2.3.1 增加ngx_http_upstream_check_module 模块
    k8s的coredns 增加外部dns解析记录
    Dockerfile的CMD总结
    redis数据转移随笔
  • 原文地址:https://www.cnblogs.com/lixingle/p/3312979.html
Copyright © 2020-2023  润新知