文件管理器與文件對接器以及復(fù)雜對象的讀寫(I/O)操作

SendBoxPaths是我自己寫的簡單對象讀寫(I/O)操作的封裝方法

*以下關(guān)于這類[SendBoxPaths ...Path]的是我調(diào)用自己封裝的方法 有興趣的朋友可以看看
http://www.lxweimin.com/p/12f2cb693b67


文件管理器(NSFileManager)

  • 此類主要是對文件進(jìn)行的操作(創(chuàng)建/刪除/改名等)以及文件信息的獲取。
  • 以下是NSFileManager的一些操作方法


    44CC2734-2923-4A31-A291-D8AF9F4F8A9C.png
44CC2734-2923-4A31-A291-D8AF9F4F8A9C.png

記得導(dǎo)包 #import "SendBoxPaths.h"

//NSFileManager的應(yīng)用
- (void)myFileManager{
    //獲取文件管理對象
    NSFileManager* fileManager = [NSFileManager defaultManager];
    //創(chuàng)建文件,并寫入數(shù)據(jù),如果該方法的返回值為YES:文件創(chuàng)建成功或者文件已經(jīng)存在,
    //第一個參數(shù):要創(chuàng)建文件的路徑
    //第二個參數(shù):要創(chuàng)建文件的內(nèi)容
    //第三個參數(shù):要設(shè)置文件的用戶組、權(quán)限、修改時間等設(shè)置。如果賦值為nil,系統(tǒng)會為文件加一些默認(rèn)設(shè)置
    //創(chuàng)建文件路徑
    NSString* path = [[SendBoxPaths cachesPath] stringByAppendingPathComponent:@"array.json"];
    //創(chuàng)建要寫入的內(nèi)容
    NSArray* array = @[@"王",@"余",@"李",@"雷"];
    //數(shù)組轉(zhuǎn)為NSData
    NSData* arrayData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
    BOOL isSuccess = [fileManager createFileAtPath:path contents:arrayData attributes:nil];
    if (isSuccess) {
        NSLog(@"isSuccess---%@",[SendBoxPaths cachesPath]);
    }else{
        NSLog(@"fail");
    }
    //讀取數(shù)據(jù)
    //先判斷該路徑下文件是否存在
    if ([fileManager fileExistsAtPath:path]) {
    
    NSData* readData = [fileManager contentsAtPath:path];
    NSArray* readArray = [NSJSONSerialization JSONObjectWithData:readData options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"readArray---%@",readArray);
    }else{
        NSLog(@"該路徑下文件不存在");
    }
    
//    
//    //將caches中的文件的array.json文件移動到documents下
//    BOOL isMove = [fileManager moveItemAtPath:path toPath:[[SendBoxPaths documentsPath] stringByAppendingPathComponent:@"newArray.json"] error:nil];
//    if (isMove) {
//        NSLog(@"移動成功");
//    }else{
//        NSLog(@"移動失敗");
//    }
    NSLog(@"documentsPath--%@",[SendBoxPaths documentsPath]);
    //將原有路徑下的文件cory到新的路徑下
    BOOL isCopy = [fileManager copyItemAtPath:path toPath:[[SendBoxPaths documentsPath] stringByAppendingPathComponent:@"copyArray.json" ] error:nil];
    if (isCopy) {
         NSLog(@"coyp成功");
    }else{
        NSLog(@"coyp失敗");
    }
    //比較文件內(nèi)容
    BOOL isEqual = [fileManager contentsEqualAtPath:path andPath:[[SendBoxPaths documentsPath] stringByAppendingPathComponent:@"copyArray.json" ]];
    if (isEqual) {
        NSLog(@"文件內(nèi)容相同");
    }else{
        NSLog(@"文件內(nèi)容不同");
    }
    
    //刪除文件
    BOOL isRemove = [fileManager removeItemAtPath:path error:nil];
    if (isRemove) {
        NSLog(@"刪除成功");
    }else{
        NSLog(@"刪除失敗");
    }
    //創(chuàng)建文件夾
    //第一個參數(shù):要創(chuàng)建的文件夾的路徑
    //第二個參數(shù):YES:如果父目錄(文件夾)不存在,創(chuàng)建的時候會將父目錄一起創(chuàng)建;NO:如果父類目錄不存在,那么文件夾就會創(chuàng)建失敗
    //第三個參數(shù):文件夾的權(quán)限
    BOOL iscreate = [fileManager createDirectoryAtPath:[[SendBoxPaths homePath] stringByAppendingPathComponent:@"AAA/bbb" ]  withIntermediateDirectories:YES attributes:nil error:nil];
    if (iscreate) {
        NSLog(@"創(chuàng)建成功");
    }else{
        NSLog(@"創(chuàng)建失敗");
    }
    NSLog(@"homePath---%@",[SendBoxPaths homePath]);
}
  • 切記要在- (void)viewDidLoad;方法里面調(diào)用

文件連接器(NSFileHandle)

  • 是非常基礎(chǔ)的只針對“文件內(nèi)容”的操作(讀取、寫入和更新)。
  • 使用場景 對文件內(nèi)容的進(jìn)行局部修改、追加內(nèi)容。
  • 使用步驟
    1.文件對接并獲取一個NSFilehandle對象
    2.讀寫操作
    3.關(guān)閉對接
  • *注意
    NSFileHandle類并沒有提供創(chuàng)建文件的功能。必須使用NSFileManager方法來創(chuàng)建文件。因此在使用下面表中的方法是,都是保證文件以及存放在,否則返回nil.
  • 文件對接器(NSFileHandle)的 一些方法
A7896233-2F8D-403A-B9D9-CC34EE11CD45.png
752D79E4-5404-41B8-A748-CF815796E1B4.png

記得導(dǎo)#import "SendBoxPaths.h" 包

//NSFileHandle的使用
-(void)myFileHandle{
    //判斷某個路徑下的文件是否存在,如果存在直接通過handle對象向里面寫入內(nèi)容;如果不存在,先創(chuàng)建該文件,在進(jìn)行操作。
    //獲取文件管理對象
    NSFileManager* fileManager = [NSFileManager defaultManager];
    NSString* path = [[SendBoxPaths documentsPath] stringByAppendingPathComponent:@"test.txt"];
    BOOL isExists = [fileManager fileExistsAtPath:path];
    if (!isExists) {
        //文件不存在  創(chuàng)建
        [fileManager createFileAtPath:path contents:nil attributes:nil];
    }
    //對文件內(nèi)容進(jìn)行操作
    //向文件寫入內(nèi)容
    NSFileHandle* fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
    //準(zhǔn)備數(shù)據(jù)
    NSString* inputString = @"111111";
    NSData* inputData = [inputString dataUsingEncoding:NSUTF8StringEncoding];
    //寫入
    [fileHandle writeData:inputData];
    //操作完畢,一定要關(guān)閉
    [fileHandle closeFile];
    //更新數(shù)據(jù)為 劉·最帥·元
    NSFileHandle* updateFileHandle = [NSFileHandle fileHandleForUpdatingAtPath:path];
    //我們要從“劉”之后寫入數(shù)據(jù),我們需要將文件偏移量設(shè)置為1,然后再開始寫入。 相當(dāng)于從1位置開始,將后面的內(nèi)容進(jìn)行替換
    [updateFileHandle seekToFileOffset:1];
    //寫入要增加的數(shù)據(jù)
    NSData* addData = [@"23" dataUsingEncoding:NSUTF8StringEncoding];
    [updateFileHandle writeData:addData];
    //操作完畢,一定要關(guān)閉
    [updateFileHandle closeFile];
    //讀取
    NSFileHandle* readFileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
    //設(shè)置要讀取的多長內(nèi)容
//    NSData* readData = [readFileHandle readDataOfLength:3];
    NSData* readData = [readFileHandle readDataToEndOfFile];//讀取所有的內(nèi)容
    //關(guān)閉
    [readFileHandle closeFile];
    //將data轉(zhuǎn)換為字符串
    NSString*  readSting = [[NSString alloc] initWithData:readData encoding:NSUTF8StringEncoding];
    NSLog(@"readSting---%@",readSting);
}
  • 切記要在- (void)viewDidLoad;方法里面調(diào)用

復(fù)雜對象的讀寫(I/O)操作

復(fù)雜對象

  • 在Foundation框架內(nèi) 不存在的數(shù)據(jù)類, 如:自定義Person類 無法再程序內(nèi)通過writeToFile:這個方法寫入到文件內(nèi)

歸檔與反歸檔

  • 如何將復(fù)雜對象寫入文件?
    復(fù)雜對象無法通過writeToFile:方法進(jìn)行數(shù)據(jù)持久化,只能通過將復(fù)雜對象轉(zhuǎn)為nSData(這個步驟就是歸檔),然后在通過writeToFile:寫入文件
  • 記住
    1.復(fù)雜對象寫入文件的過程(復(fù)雜對象 ->歸檔->NSData->writeToFile:)
    2.從文件讀取復(fù)雜對象過程(讀取文件->NSData->反歸檔->復(fù)雜對象)
  • 復(fù)雜對象所屬的類要遵守<NSCoding>協(xié)議
  • 實(shí)現(xiàn)協(xié)議中的兩個方法
    1.-(void)encodeWithCoder:(NSCoder *)aCoder;
    2.-(id)initWithCoder:(NSCoder *)aDecoder;

代碼示例

首先建一個Person類

#import <Foundation/Foundation.h>
//要對復(fù)雜對象進(jìn)行歸檔,必須遵循一個協(xié)議
@interface Person : NSObject<NSCoding>
@property (nonatomic,strong) NSString* name;
@property (nonatomic,assign) int age;
@end
#Person的.m
#import "Person.h"
@implementation Person
//歸檔的過程:相當(dāng)于將復(fù)雜對象轉(zhuǎn)NSData類型,為了寫入文件。
-(void)encodeWithCoder:(NSCoder *)aCoder{
    //歸檔的過程是將當(dāng)前對象每一個屬性都進(jìn)行編碼。
    //第一個參數(shù):要進(jìn)行編碼的屬性的值
    //第二個參數(shù):為屬性的值加標(biāo)記,加標(biāo)記是為了解碼使用
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInt:self.age forKey:@"age"];
    NSLog(@"調(diào)用歸檔的方法");
}
//反歸檔:將NSData轉(zhuǎn)換為復(fù)雜對象,為了讀取使用。
-(id)initWithCoder:(NSCoder *)aDecoder{
    NSLog(@"調(diào)用反歸檔的方法");
    self = [super init];
    if (self) {
        //解碼 從文件中讀取出來值,賦值給對應(yīng)的屬性
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [aDecoder decodeIntForKey:@"age"];
    }
    return self;
}
@end

在ViewController.m中記得導(dǎo)包

#import "SendBoxPaths.h"

#import "Person.h"

*代碼示例

//歸檔的過程
- (void)myEncoder{
    //需要聲明創(chuàng)建一個person對象用來歸檔
    Person* person = [[Person alloc] init];
    person.name = @"劉元";
    person.age = 123;
    //需要創(chuàng)建一個可變的data對象,用來存放歸檔好的person對象
    NSMutableData* mData = [[NSMutableData alloc]init];
    //創(chuàng)建歸檔工具對象
    //參數(shù)為要承接歸檔完成的復(fù)雜對象:
    NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:mData];
    //歸檔
    //第一個參數(shù):要?dú)w檔的復(fù)雜對象
    //第二個參數(shù):標(biāo)記,為了反歸檔使用
    [archiver encodeObject:person forKey:@"person"];
    //歸檔結(jié)束,一定調(diào)用下面這個方法,要不然mData中不會有值
    [archiver finishEncoding];
    //將MData持久化到本地文件
    NSString* path = [[SendBoxPaths documentsPath]stringByAppendingPathComponent:@"archiver.data"];
    [mData writeToFile:path atomically:YES];
}
//反歸檔
-(void)unArchiver{
    //將剛才歸檔文件中的data數(shù)據(jù)讀取出來,以便反歸檔使用
    NSString* path = [[SendBoxPaths documentsPath]stringByAppendingPathComponent:@"archiver.data"];
    NSData* data = [NSData dataWithContentsOfFile:path];
    //初始化一個反歸檔工具
    NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    //反歸檔
    Person* person = [unarchiver decodeObjectForKey:@"person"];
    //反歸檔結(jié)束的方法,必須調(diào)用
    [unarchiver finishDecoding];
    NSLog(@"name === %@,age === %d",person.name,person.age);
}
  • 切記要在- (void)viewDidLoad;方法里面調(diào)用

不足之處希望大家見諒,我會在更新

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 本章包含的四個知識點(diǎn): 一、沙盒機(jī)制 二、簡單對象的寫入與讀取 三、文件管理器 四、復(fù)雜對象的寫入與讀取 一、 i...
    逗逗豆豆笑閱讀 1,444評論 0 5
  • 下面是我最近兩年學(xué)習(xí)OC中的一些基礎(chǔ)知識,對于學(xué)習(xí)OC基礎(chǔ)知識的人可能有些幫助,拿出來分享一下,還是那句話不喜勿噴...
    小小趙紙農(nóng)閱讀 2,635評論 1 7
  • 一、數(shù)據(jù)持久化概述 數(shù)據(jù)持久化就是數(shù)據(jù)的永久存儲。其本質(zhì)是將數(shù)據(jù)保存為文件,存到程序的沙盒中。 1、數(shù)據(jù)持久化的方...
    lilinjianshu閱讀 628評論 0 1
  • iOS 開発の結(jié)構(gòu) 畫面 UI UIWebview [[UIApplication sharedApplicati...
    RencaiXiong閱讀 599評論 0 0
  • 本文結(jié)構(gòu) 參考孟巖老師的文章,對本文結(jié)構(gòu)如下劃分 基本數(shù)據(jù)類型基本語法數(shù)組和其他集合類基本輸入輸出和文件處理,輸入...
    不抄完整本三國不改名閱讀 538評論 0 1