歸檔NSKeyedArchiver解歸檔NSKeyedUnarchiver與檔案管理類NSFileManager (檔案操作),

來源:互聯網
上載者:User

歸檔NSKeyedArchiver解歸檔NSKeyedUnarchiver與檔案管理類NSFileManager (檔案操作),

==========================

檔案操作

==========================

一、歸檔NSKeyedArchiver

1.第一種方式:儲存一種資料。

         // 歸檔

        // 第一種寫法

        // 對象--檔案

        NSArray* array = [[NSArray alloc]initWithObjects:@"zhang", @"wang", @"li", nil];

        NSString* filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.txt"];

        BOOL success = [NSKeyedArchiver archiveRootObject:array toFile:filePath];

        if (success) {

            NSLog(@"儲存成功");

        }

        

        // 解歸檔

        NSArray* arr = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

        NSLog(@"%@",arr);

 

2.第二種方式:儲存並行資料(儲存多種資料)。

        //  第二種寫法:

        NSArray* array = @[@"one", @"two", @"three"];

        NSDictionary* dic = @{@"key":@"value"};

        NSString* str = @"我是中國人,我愛中國";

        

        // NSData 資料流類

        // 用來儲存複雜的資料,把複雜的資料轉成資料流格式,可以方便進行儲存和傳輸。

        // 例如:圖片、大檔案

        // 斷點續傳,假片有20M大,

        // 發郵件:添加附件

        NSMutableData* data = [[NSMutableData alloc]init];

        

        // initForWritingWithMutableData 指定要寫入的資料流檔案

        NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];

        

        // 編碼資料,參數一:要準備編碼的資料;參數二:編碼資料的key,key隨便寫

        [archiver encodeObject:array forKey:@"array"];

        [archiver encodeObject:dic forKey:@"dic"];

        [archiver encodeObject:str forKey:@"str"];

        

        // 編碼完成

        [archiver finishEncoding];

        

        // 指定檔案路徑

        NSString* filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"file2"];

        

        // 寫入檔案

        [data writeToFile:filePath atomically:YES];

        

        // =======================================

        // 下部分

        

        // 先把路徑下的檔案讀入資料流中

        NSMutableData* fileData = [[NSMutableData alloc]initWithContentsOfFile:filePath];

        

        // 把資料流檔案讀入到了 解歸檔中 

        NSKeyedUnarchiver* unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:fileData];

        

        // 進行解歸檔

        NSArray* UnArray = [unArchiver decodeObjectForKey:@"array"];

        NSDictionary* UnDic = [unArchiver decodeObjectForKey:@"dic"];

        NSString* UnStr = [unArchiver decodeObjectForKey:@"str"];

        

        // 列印

        NSLog(@"%@\n%@\n%@\n",UnArray,UnDic,UnStr);

 

3.第三種歸檔方式:對類對象進行歸檔

1.先在類的標頭檔中實現<NSCoding>協議

2.在.m中重新編碼和解碼協議。

// 重新initWithCoder 解碼方法

- (id) initWithCoder: (NSCoder *)aDecoder

{

    NSLog(@"我是解碼方法,我負責解碼");

    self = [super init];

    if (self) {

        _name = [aDecoder decodeObjectForKey:@"name"];

        _phone = [aDecoder decodeObjectForKey:@"phone"];

        _address = [aDecoder decodeObjectForKey:@"address"];

    }

    return  self;

}

 

//重新編碼方法

- (void) encodeWithCoder: (NSCoder *)aCoder

{

    [aCoder encodeObject:_name forKey:@"name"];

    [aCoder encodeObject:_phone forKey:@"phone"];

    [aCoder encodeObject:_address forKey:@"address"];

}

 

//【注】forKey:是字串;編碼方法和解碼方法字串要一致

 

二、NSFileManager 檔案管理類

 

1.1、檔案路徑

        // 根路徑

        NSString* homePath = NSHomeDirectory();

        NSLog(@"%@",homePath);

        

        oc中有三個目錄是可以操作的。

         1.Documents // 文稿目錄

         2.tmp // 臨時目錄:程式退出的時候,臨時目錄內容可能會被情況

         3.library--->Cache // 緩衝目錄 // app目錄下

    

        

        // 擷取Documents  目錄

        // 寫法一

        NSString* Documents = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

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

        

        // 寫法二

        NSString* Documents1 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES) objectAtIndex:0];

        NSLog(@"Documents : %@",Documents1);

        

        // 擷取應用程式的主目錄

        NSString* userName = NSUserName();

        NSString* rootPath = NSHomeDirectoryForUser(userName);

        NSLog(@"app root path:%@",rootPath);

        

        // 擷取cache目錄

        NSString* cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];

        NSLog(@"cache :%@",cachePath);

        

        // 擷取tmp目錄

        NSString* tmpPath = NSTemporaryDirectory();

        NSLog(@"tmp:%@",tmpPath);

 

1.2、建立目錄和檔案

       // 擷取根目錄

        NSString* homePath = NSHomeDirectory();

        

        // 建立了一個檔案管理工具

        NSFileManager* fileMgr = [NSFileManager defaultManager];

        

        // 拼接出想要建立的檔案路徑

        NSString* filePath = [NSString stringWithFormat:@"%@/myFolder",homePath];

        

        // 建立檔案目錄

        // 第一個參數傳入想要建立的檔案目錄,第二個參數指導是否建立不存在的檔案夾,yes代表建立

        BOOL isOk = [fileMgr createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];

        if (isOk) {

            NSLog(@"建立檔案目錄成功");

        }

        

        NSString* string = @"我愛記歌詞";

        // 把內容寫入到指定路徑下的指定檔案中

        BOOL isWriteOk = [string writeToFile:[NSString stringWithFormat:@"%@/1.txt",filePath] atomically:YES encoding:NSUTF8StringEncoding error:nil];

        if (isWriteOk) {

            NSLog(@"寫入檔案成功");

        }

        

        // 數組儲存

        NSArray* array = @[@"我是一", @"我是三", @"我是周7"];

        BOOL isWriteOK1 = [array writeToFile:[NSString stringWithFormat:@"%@/2.txt",filePath] atomically:YES];

        if (isWriteOK1) {

            NSLog(@"數組寫入檔案成功");

        }

        

        // 字典儲存

        NSDictionary* dic = @{@"key":@"value"};

        BOOL isWriteOK2 = [dic writeToFile:[NSString stringWithFormat:@"%@/3.txt",filePath] atomically:YES];

        if (isWriteOK2) {

            NSLog(@"字典寫入檔案成功");

        }

 

2.對檔案進行重新命名

 

        // 擷取根目錄

        NSString* homePath = NSHomeDirectory();

        

        // 建立了一個檔案管理工具

        NSFileManager* fileMgr = [NSFileManager defaultManager];

        

        // 拼接出想要建立的檔案路徑

        NSString* filePath = [NSString stringWithFormat:@"%@/myFolder/1.txt",homePath];

        

        [fileMgr moveItemAtPath:filePath toPath:[NSString stringWithFormat:@"%@/ai.txt",homePath] error:nil];

 

3.刪除一個檔案

         // 聲明了一個錯誤資訊的對象

        NSError* error;

        

        // 擷取根目錄

        NSString* homePath = NSHomeDirectory();

        

        // 建立了一個檔案管理工具

        NSFileManager* fileMgr = [NSFileManager defaultManager];

        

        // 拼接出想要建立的檔案路徑

        NSString* filePath = [NSString stringWithFormat:@"%@/myFolder/3.txt",homePath];

        

        // 刪除檔案

        // 如果方法執行返回是NO,error會儲存錯誤資訊,如果方法執行返回是YES,error = nil

        BOOL isok = [fileMgr removeItemAtPath:filePath error:&error];

        if (isok) {

            NSLog(@"刪除檔案成功");

        }

        else

        {

            NSLog(@"刪除檔案失敗");

            // 列印錯誤資訊

            NSLog(@"%@",error.localizedDescription);

        }

 

Δ【擴充】NSError類,是一個錯誤資訊類

        // 刪除檔案

        // 如果方法執行返回是NO,error會儲存錯誤資訊,如果方法執行返回是YES,error = nil

        BOOL isok = [fileMgr removeItemAtPath:filePath error:&error];

 

∆4.刪除目錄下的所有檔案

        // 擷取根目錄

        NSString* homePath = NSHomeDirectory();

        

        // 建立了一個檔案管理工具

        NSFileManager* fileMgr = [NSFileManager defaultManager];

        

        // 拼接出想要建立的檔案路徑

         NSString* filePath = [NSString stringWithFormat:@"%@/myFolder/3.txt",homePath];

        

        // 如果刪除的目錄中不帶具體的檔案,則刪除的是整個目錄

        [fileMgr removeItemAtPath:[NSString stringWithFormat:@"%@/myFolder/",homePath] error:nil];

 

5.擷取目錄下的所有檔案

        // 擷取根目錄

        NSString* homePath = NSHomeDirectory();

        

        // 建立了一個檔案管理工具

        NSFileManager* fileMgr = [NSFileManager defaultManager];

        

        // 拼接出想要建立的檔案路徑

        NSString* filePath = [NSString stringWithFormat:@"%@/myFolder/",homePath];

        

        // 擷取目前的目錄下的所有檔案,包括隱藏檔案

        NSArray* allFile = [fileMgr contentsOfDirectoryAtPath:filePath error:nil];

        NSLog(@"%@",allFile);

        

        // 擷取目前的目錄以及子目錄的所有檔案

        NSArray* subAllFile = [fileMgr subpathsOfDirectoryAtPath:filePath error:nil];

        

6.檔案的屬性

       // 擷取根目錄

        NSString* homePath = NSHomeDirectory();

        

        // 建立了一個檔案管理工具

        NSFileManager* fileMgr = [NSFileManager defaultManager];

        

        // 拼接出想要建立的檔案路徑

        NSString* filePath = [NSString stringWithFormat:@"%@/myFolder/3.txt",homePath];

        

        NSDictionary* fileAttribute = [fileMgr fileAttributesAtPath:filePath traverseLink:YES];

        // 擷取檔案的屬性

        NSData* data = [fileAttribute objectForKey:NSFileModificationDate];

        NSLog(@"檔案的建立日期:%@",data);

       // 擷取檔案屬性2(*)

        NSDictionary* dic1 = [fileMgr attributesOfItemAtPath:filePath error:nil];

        NSLog(@"屬性列印 %@",dic1);

        // 檔案佔多少位元組

        NSNumber * number = [fileAttribute objectForKey:NSFileSize];

        NSLog(@"檔案的大小:%@",number);

        // 判斷檔案是否存在

       NSFileManager *manager = [NSFileManager defaultManager];

       BOOL isExist = [manager  fileExistsAtPath:filePath];

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.