zoukankan      html  css  js  c++  java
  • IOS中的NSData和NSFileManager例子微解

    //NSData遵循NSCopying NSCoding协议,它提供面向对象的数组存储为字节

        //适用与读写文件,而读写文件的时候需要一个缓冲区,而NSDate就提供了这么一个缓存区

        

        //定义一个char类型的字符串

        const char * string = "Hi there ,this is a C string";

        //建立缓冲区,把字符串添加进去

        NSData * data = [NSData dataWithBytes:string length:strlen(string)+1];

        //输出

        NSLog(@"data is %@",data);

        NSLog(@"%lu bytes string is '%s'",[data length],[data bytes]);

        

        

        

        //定义一个字符串,保存一个路径

        NSString * path = @"/tmp/ver.txt";

        //把这个保存路径的字符串保存到另一个文件中  encoding是编码

        [path writeToFile:@"/tmp/string.txt" atomically:YES encoding:NSASCIIStringEncoding error:nil];

        

        //添加一个数组   并添加几个字符串

        NSArray * phrase;

        phrase = [NSArray arrayWithObjects:@"i",@"good",@"seem",@"to",nil];

        //把数组写入(上面定义的字符串路径)的文件中

        [phrase writeToFile:path atomically:YES];

        //打印 

        NSLog(@"%@",phrase);

        

        //创建文件管理器

        /*NSFileManager可以用来查询单词库目录,创建,重命名,删除目录以及获取/设置文件属性的方法*/

        NSFileManager * fm;

        fm = [NSFileManager defaultManager];

        //创建缓冲区,利用NSFileManager对象来获取文件中的内容,也就是这个文件的属性可修改

        NSData * fileData;

        fileData = [fm contentsAtPath:@"/tmp/ver.txt"];

        //打印

        NSLog(@"file data is %@",fileData);

        //对NSData对象进行判断

        if(fileData)

        {

            NSLog(@"file read success");

        }

        else

        {

            NSLog(@"file read failed");

        }

        //定义一个布尔类型的对象

        BOOL ifsucess;

        //在objective-c种,正确是YES 错误是NO

        ifsucess = NO;

        //获取上面fileData对象中通过NSFileManager对象获取的文件中的内容,然后再创建一个新的路径,并存储

        ifsucess = [fm createFileAtPath:@"/tmp/test4.txt" contents:fileData attributes:nil];

        //对布尔型对象进行判断

        if(ifsucess)

        {

            NSLog(@"create file sucess");

        }

        else 

        {

            NSLog(@"create file failed");

        }

  • 相关阅读:
    CHOCBase
    iOS 12中无法获取WiFi的SSID了?
    如何打开Assets.car文件
    博客园美化资源网站链接
    xcode工程配置绝对路径与相对路径
    UIControl事件
    UIButton属性
    UIAlertView
    UIActivityIndicatorView
    NSAttributedString
  • 原文地址:https://www.cnblogs.com/yuyu-2012/p/4812613.html
Copyright © 2011-2022 走看看