OC 文件操作 持久化

来源:互联网 发布:苹果手机扫描软件 编辑:程序博客网 时间:2024/05/29 03:17

2016.9.6  OC  第八天 文件操作

相对路径、绝对路径两种

相对路径:相对于某个参照物的位置

绝对位置:固定位置

~用户根目录   .  当前目录     ..当前目录的上一级目录


NSCoding协议:数据持久化  


N框架提供对文件、路径操作的类创建文件、判断文件是否存在、拷贝、删除



写入文件必须保证文件存在(不会自动创建文件)

文件句柄;用来对数据流的操作

1、打开文件

2、操作(写入、输出)

3、关闭文件


/*

 路径:相对路径、绝对路径

 相对路径:相对于某个参照物的一个位置

 绝对路径:固定位置

 ~  :用户根目录            ~/main.m

 .  : 当前目录            ./main.m

 .. : 当前目录的上一级目录  ../main.m

 

 

 NSCoding协议:数据持久化

 

 

 缓存:NSData NSMutableData

 

 

 NSFileManager: Foundation框架提供对文件、路径操作的类

 创建文件、判断文件是否存在、拷贝、删除...

 */


#import <Foundation/Foundation.h>

#import "AddressCard.h"

#import "AddressCardManager.h"




NSString * filePath = @"address.txt";

//归档操作

void test1() {

    AddressCard * card1 = [[AddressCard alloc] init];

    card1.name = @"Tom";

    card1.email = @"Tom@gmile.com";

    

    //完成写入功能(调用encodeWithCoder)

    BOOL result = [NSKeyedArchiver archiveRootObject:card1

                                              toFile:filePath];

    if (result) {

        NSLog(@"写入成功");

    } else

    {

        NSLog(@"写入失败");

    }

}

//数组写入

void test11() {

    AddressCard *a1 = [[AddressCard alloc] init];

    a1.name = @"a1";

    a1.email = @"345678io";

    

    AddressCard *a2 = [[AddressCard alloc] init];

    a2.name = @"a2";

    a2.email = @"sdfghjk";

    

    AddressCardManager *aa = [[AddressCardManager alloc] initWith];

    [aa addA:a1];

    [aa addA:a2];

    

    

    BOOL result = [NSKeyedArchiver archiveRootObject:aa toFile:@"abc.docx"];

    if (result) {

        NSLog(@"en");

    } else {

        NSLog(@"no");

    }

}

//解档操作(读取文件输出)

void test2() {

    AddressCard * card2 = [NSKeyedUnarchiver

                           unarchiveObjectWithFile:filePath];

    [card2 description];

}

//数组读取

void test22() {

    AddressCardManager * card = [NSKeyedUnarchiver

                           unarchiveObjectWithFile:@"aa.docx"];

    [card print];

}

//单纯数组、字典写入、读取

void test12() {

    //数组写入

    /*

    AddressCard *a1 = [[AddressCard alloc] init];

    a1.name = @"1";

    a1.email = @"1.com";

    

    AddressCard *a2 = [[AddressCard alloc] init];

    a2.name = @"2";

    a2.email = @"2.com";

    

    AddressCard *a3 = [[AddressCard alloc] init];

    a3.name = @"3";

    a3.email = @"3.com";

    

    NSMutableArray *array = [[NSMutableArray alloc]init];

    [array addObject:a1];

    [array addObject:a2];

    [array addObject:a3];

    

    BOOL result = [NSKeyedArchiver archiveRootObject:array toFile:@"aabbcc.docx"];

    if (result) {

        NSLog(@"直接写入数组成功");

    } else {

        NSLog(@"直接写入数组失败");

    }

    */

    //数组读取

    

    NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:@"aabbcc.docx"];

    NSLog(@"%ld",[array count]);

    

    for (id ele in array) {

        [(AddressCard*)ele description];

    }

     

    

    //字典写入

    /*

    AddressCard *a1 = [[AddressCard alloc] init];

    a1.name = @"1";

    a1.email = @"1.com";

    

    AddressCard *a2 = [[AddressCard alloc] init];

    a2.name = @"2";

    a2.email = @"2.com";

    

    AddressCard *a3 = [[AddressCard alloc] init];

    a3.name = @"3";

    a3.email = @"3.com";

    

    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];

    [dic setObject:a1 forKey:@"A1"];

    [dic setObject:a2 forKey:@"A2"];

    [dic setObject:a3 forKey:@"A3"];

    BOOL result = [NSKeyedArchiver archiveRootObject:dic toFile:@"aabbccdd.docx"];

    if (result) {

        NSLog(@"直接写入字典成功");

    } else {

        NSLog(@"直接写入字典失败");

    }

    */

    

    //读取字典内容->使用key获取value

    /*

    NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithFile:@"aabbccdd.docx"];

    

    //获取字典中所有key

    NSArray *keyArray = [dic allKeys];

    

    //快速遍历key集合

    for (NSString *key in keyArray) {

        //根据key获取valuevalue强转成AddrressCard*,调用description方法

        [(AddressCard*)[dic objectForKey:key] description];

    }

    */

}

//读取文件内容到缓存区(读取前确保文件存在)

void test3() {

    //文件读取到缓存

    NSData * data = [NSData dataWithContentsOfFile:filePath];

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

}

//缓存内容写入到文件中

void test4() {

    NSData * data = [NSData dataWithContentsOfFile:filePath];

    BOOL write = [data writeToFile:@"address2.txt" atomically:YES];

    if (write) {

        NSLog(@"sucess!");

    } else {

        NSLog(@"fail");

    }

}

//NSFileManager操作

void test5() {

    

    //defaultManager:一个类方法,用来创建对象

    NSFileManager *fm = [NSFileManager defaultManager];

    //获取文件属性

    NSError* error = nil;

    NSDictionary* attribute = [fm attributesOfItemAtPath:filePath error:&error];

    //查看文件大小

    int filesize = [[attribute objectForKey:NSFileSize] intValue];

    

    NSLog(@"size = %d",filesize);


    

    //使用fm读取文件内容到缓存

    NSData* data = [fm contentsAtPath:filePath];

    //解档缓存内容成对象

    AddressCard* card = [NSKeyedUnarchiver unarchiveObjectWithData:data];

    NSLog(@"card %@",card);

    

    

    //使用fm创建文件

    BOOL result = [fm createFileAtPath:@"address3.txt" contents:data attributes:nil];

    if (result) {

        NSLog(@"success...");

    } else {

        NSLog(@"fail...");

    }

    


    //使用fm删除文件

    BOOL result1 = [fm removeItemAtPath:@"address3.txt" error:&error];

    if (result1) {

        NSLog(@"success...");

    } else {

        NSLog(@"fail...");

    }

    

    

    //判断文件是否存在

    BOOL result2 = [fm fileExistsAtPath:filePath];

    if (result2) {

        NSLog(@"存在...");

    } else {

        NSLog(@"不存在...");

    }



    //拷贝

    

    BOOL result3 = [fm copyItemAtPath:filePath toPath:@"address4.txt"

                 error:&error];

    if (result3) {

        NSLog(@"enheng...");

    } else {

        NSLog(@"no no no ...");

    }

}

//路径操作

void test6() {

    NSFileManager *fm = [NSFileManager defaultManager];

    //NSLog(@"%@", NSHomeDirectory()); //获取用户主目录

    

    NSString* path =[fm currentDirectoryPath]; //获取用户当前目录

    //NSLog(@"%@",path);

    

    

    NSLog(@"%@",[path stringByAppendingPathComponent:@"AddredCard.txt"]); //路径追加自动添加'/'

    NSLog(@"%@",[path stringByAppendingFormat:@"AddredCard.txt"]); //追加路径不会自动添加'/'

}



//纯文件操作写入(不包涵路径)

//文件句柄:用来对数据流的操作,

//1、打开文件 2、操作(输出、写入) 3、关闭文件

void test7() {

    

    NSString *homePath=@"/Users/caoyang/Desktop/a.txt";

    

    //写入文件必须预先让文件存在(不会自动创建文件)

    NSFileManager* fm = [NSFileManager defaultManager];

    if(![fm fileExistsAtPath:homePath]){

        [fm createFileAtPath:homePath contents:nil attributes:nil];

    }

    

    //创建写入对象

    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:homePath];

    

    [fileHandle seekToEndOfFile];//光标移动到文件最后

    

    NSString *str=@"测试加入的数据为";

    NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];

    

    [fileHandle writeData:data];

    [fileHandle closeFile];

}

//纯文件操作读取(不包涵路径)

void test8() {

    NSString *homePath=@"/Users/caoyang/Desktop/a.txt";

    //创建一个读文件句柄

    NSFileHandle *fileHandle=[NSFileHandle fileHandleForReadingAtPath:homePath];

    

    //获取文件长度

    NSUInteger length= [fileHandle availableData].length;

    NSLog(@"length = %ld",length);

    

    [fileHandle seekToFileOffset:0]; //偏移

    

    //读取文件到缓存

    NSData *data=[fileHandle readDataToEndOfFile];

    NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"===%@",str);

}


int main(int argc, const char * argv[]) {

    @autoreleasepool {

        test8();

    }

    return 0;

}

0 0
原创粉丝点击