1. 程式人生 > >【iOS】第03講 檔案讀寫/NSArray/NSData/NSFileManager/NSFileHandle

【iOS】第03講 檔案讀寫/NSArray/NSData/NSFileManager/NSFileHandle

一、沙盒

   模擬器上的沙盒目錄路徑

   ~/Library/Application Support/iPhone Simulator/6.0/Applications


   

              

   獲取沙盒的目錄路徑

    //NSHomeDirectory : 獲取沙盒的目錄路徑

   NSString *homePath =NSHomeDirectory

();

   NSLog(@"沙盒目錄:%@",homePath);

    

   NSString *docPath1 = [NSStringstringWithFormat:@"%@/Documents",homePath];

   NSString *docPath2 = [homePathstringByAppendingFormat:@"/Documents"];

    

    NSLog(@"docPath1=%@,docPath2=%@"

,docPath1,docPath2);


二、檔案管理

   2.1 NSString處理路徑

    //NSString處理路徑

    NSString *path =@"/Users/apple/file.text";

    //1.獲取路徑的組成部分結果:("/","Users","apple","file.text")

   NSArray *components = [pathpathComponents];

    

    //2.路徑的最後一個組成部分結果:file.text

   NSString *lastName = [pathlastPathComponent];

    

    //3.追加檔案或目錄結果:/Users/apple/file.text/app.text

   NSString *filePath = [pathstringByAppendingString:@"app.text"];


    //4.刪除最後的組成部分/副檔名

    NSString *deletePath = [pathstringByDeletingLastPathComponent];

    NSString *deleteExt = [pathstringByDeletingPathExtension];


    //5.獲取副檔名/追加副檔名

   NSString *ext = [pathpathExtension];

    NSString *extPath = [pathstringByAppendingPathExtension:@"jpg"];



   2.2 NSData資料處理

     NSData是一種對資料的抽象

     任何資料都可以通過NSData來儲存,NSMutableData是可變的,繼承於NSData

       

   

   2.3 NSFileManager

      NSFileManager主要對檔案進行管理,主要功能:

                                    

      NSFileManager管理檔案的常用方法

    //NSHomeDirectory : 獲取沙盒的目錄路徑

    NSString *homePath =NSHomeDirectory();

    NSLog(@"沙盒目錄:%@",homePath);

    

    //1.建立一個檔案並寫入資料

    NSString* filePath = [homePathstringByAppendingPathComponent:@"Documents/1.jpg"];

    

    //NSFileManager 只能有一個例項物件,不能用alloc建立

    NSFileManager* fileManager = [NSFileManagerdefaultManager];

    BOOL result = [fileManagercreateFileAtPath:filePathcontents:nilattributes:nil];

    

    if(result)

        NSLog(@"file create success");

    else

        NSLog(@"file create fail");

    

    //2.建立資料夾

    filePath = [homePath stringByAppendingPathComponent:@"Documents/model/Smile/pic/01"];

    

    NSLog(@"%@",filePath);

    

    NSError *error;

    result = [fileManager createDirectoryAtPath:filePathwithIntermediateDirectories:YESattributes:nilerror:&error];

    

    if(result)

        NSLog(@"file dir create success");

    else

        NSLog(@"file dir create fail");

    

    //3.讀取檔案中的資料

    filePath = [homePath stringByAppendingPathComponent:@"Documents/1.jpg"];

    NSData *data = [fileManagercontentsAtPath:filePath];

    NSString *string = [[NSStringalloc] initWithData:dataencoding:NSUTF8StringEncoding];

    NSLog(@"%@",string);

    

    //4.移動檔案

    NSString* targetPath = [homePathstringByAppendingPathComponent:@"Documents/model/Smile/pic/01/1.jpg"];

    result = [fileManager moveItemAtPath:filePathtoPath:targetPath error:nil];

    

    if(result)

        NSLog(@"file move success");

    

    //5.複製檔案

    result = [fileManager copyItemAtPath:targetPathtoPath:filePath error:nil];

    if(result)

        NSLog(@"file copy success");

    

    //6.刪除檔案

    BOOL fileExist = [fileManagerfileExistsAtPath:filePath];

    if(fileExist)

    {

        result = [fileManager removeItemAtPath:filePatherror:nil];

        if(result)

            NSLog(@"file remove success");

    }

    

    //7.獲取檔案大小

    NSDictionary* fileAttr = [fileManagerattributesOfItemAtPath:targetPatherror:nil];

    NSLog(@"%@",fileAttr);

    

    NSNumber *fileSize = [fileAttrobjectForKey:NSFileSize];

    int sizeValue = [fileSizeintValue];

    

    NSLog(@"檔案大小%d",sizeValue);


   2.4 寫檔案

     陣列NSArray、字典NSDictionary、字串NSString、NSData 都是容納資料的

     NSArray、NSDictionary中只能

         存入NSNumber、NSString、NSData、NSDate、NSArray、NSDictionary

          才能寫入檔案,寫入後以xml方式儲存

     它們都有一個writeToFile方法將資料寫入檔案

                 

    

    //NSString 讀寫檔案

    filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];

    NSString *s =@"Hello iOS";

    

    [s writeToFile:filePathatomically:YESencoding:NSUTF8StringEncodingerror:nil];

    

    NSString *fileString = [NSStringstringWithContentsOfFile:filePathencoding:NSUTF8StringEncodingerror:nil];

    

    NSLog(@"%@",fileString);

    

    //NSData 讀寫檔案

    NSData *data = [[NSDataalloc] initWithContentsOfFile:filePath];

    fileString = [[NSStringalloc] initWithData:dataencoding:NSUTF8StringEncoding];

    NSLog(@"%@",fileString);

    

    [data writeToFile:filePathatomically:YES];

    

    //NSArray 讀寫檔案

    filePath = [homePath stringByAppendingPathComponent:@"Documents/array.plist"];

    

    NSString *s1 =@"voron";

    NSString *s2 =@"lisa";

    

    NSArray *array = [[NSArrayalloc] initWithObjects:s1,s2,nil];

    

    result = [array writeToFile:filePathatomically:YES];

    

    if(result)

        NSLog(@"NSArray write to file success");

    

    NSArray* readArray = [[NSArrayalloc] initWithContentsOfFile:filePath];

    for(NSString *sin readArray)

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

    

    //NSDictionary 讀寫檔案

    NSDictionary *dict =@{

                          @"name":@"jack",

                          @"birth":[NSDatedate],

                          @"age":@22

                          };

    filePath = [homePath stringByAppendingPathComponent:@"Documents/dict.plist"];

    result = [dict writeToFile:filePathatomically:YES];

    

    NSDictionary *readDict = [NSDictionarydictionaryWithContentsOfFile:filePath];

    NSLog(@"%@",readDict);


    2.5 NSFileHandle         NSFileHandle主要是對檔案內容進行讀取和寫入操作             不能建立檔案        

    //NSFileHandle

    //1.追加寫入資料

    //建立一個寫入的FileHandle物件

    NSFileHandle *writeHandle = [NSFileHandlefileHandleForWritingAtPath:filePath];

    [writeHandle seekToEndOfFile];

    NSString *appendString =@"appending data";

    NSData* data = [appendStringdataUsingEncoding:NSUTF8StringEncoding];

    

    [writeHandle writeData:data];

    

    [writeHandle closeFile];

    

    //2.定位讀取

    NSFileHandle *readHandle = [NSFileHandlefileHandleForReadingAtPath:filePath];

    //獲得檔案長度

    NSDictionary* fileAttr = [fileManagerattributesOfItemAtPath:filePatherror:nil];

    

    NSNumber *fileSize = [fileAttrobjectForKey:NSFileSize];

    unsignedlong long sizeValue = [fileSizelongLongValue];

    //設定偏移量

    [readHandle seekToFileOffset:sizeValue/2];

    

    data = [readHandle readDataToEndOfFile];

    

    NSString *dataString = [[NSStringalloc] initWithData:dataencoding:NSUTF8StringEncoding];

    NSLog(@"%@",dataString);

       

三、檔案讀寫類和檔案管理類實現

    3.1 File類

      File.h

#ifndef File_h

#define File_h


enum FileType

{

    FT_WriteOnly,

    FT_ReadOnly,

    FT_ReadWrite

};


class File

{

public:

    File(const char* relPath,NSString* absolutePath);

    virtual ~File();

    

    void Open(FileType type);

    

    void Write(const char* data,int size);

    

    void Read(char*& data,int size);

    

    void Close();

    

private:

    NSFileHandle *fileHandle;

    

    const char* relativePath;

    NSString* absolutePath;

};


#endif /* File_h */


      File.mm

#import <Foundation/Foundation.h>

#import "File.h"


File::File(const char* relPath,NSString* absPath)

:relativePath(relPath),

absolutePath(absPath)

{

    //

}


File::~File()

{

    //

}


void File::Open(FileType type)

{

    if(FT_WriteOnly == type)

    {

        fileHandle = [NSFileHandle fileHandleForWritingAtPath:absolutePath];

        [fileHandle seekToEndOfFile];

    }

    else if(FT_ReadOnly == type)

    {

        fileHandle = [NSFileHandle fileHandleForReadingAtPath:absolutePath];

    }

    else if(FT_ReadWrite == type)

    {

        fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:absolutePath];

    }

}


void File::Write(const char *data, int size)

{

    NSData *data_ = [NSData dataWithBytes:data length:size];

    

    [fileHandle writeData:data_];

    

}


void File::Read(char *&data, int size)

{

    //

}


void File::Close()

{

    [fileHandle closeFile];

}


    3.2 FileManager類

      FileManager.h

#ifndef FileManager_h

#define FileManager_h

#include <map>

#include "Singleton.h"

#include "File.h"

using std::map;


class FileManager : public Singleton<FileManager>

{

public:

    FileManager();

    virtual ~FileManager();

    

    File* CreateFile(const char* relativePath);

    

private:

    NSFileManager *fileManager;

    

    NSString *mainPath;

    

    map<const char*,File*> fileMap;

};


#endif /* FileManager_h */


      FileManager.mm

#import <Foundation/Foundation.h>

#import "FileManager.h"


template<>

FileManager* Singleton<FileManager>::ms_pSingleton(0);


FileManager::FileManager()

{

    fileManager = [NSFileManager defaultManager];

    

    NSString *homePath = NSHomeDirectory();

    mainPath = [homePath stringByAppendingPathComponent:@"Documents"];


}


FileManager::~FileManager()

{

}


File* FileManager::CreateFile(const char *relativePath)

{

    NSString* relPath = [NSString stringWithUTF8String:relativePath];

    NSString* relativePathWithoutLast = [relPath stringByDeletingLastPathComponent];

    

    NSString* filePath = [mainPath stringByAppendingPathComponent:relativePathWithoutLast];

    

    NSLog(@"%@",filePath);

    BOOL fileExist = [fileManager fileExistsAtPath:filePath];

    if(!fileExist)

    {

        BOOL result = [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];

    

        if(result)

            NSLog(@"file dir create success");

        else

            NSLog(@"file dir create fail");

        

    }

    

    filePath = [mainPath stringByAppendingPathComponent:relPath];

    NSLog(@"%@",filePath);

    

    fileExist = [fileManager fileExistsAtPath:filePath];

    if(!fileExist)

    {

        BOOL result = [fileManager createFileAtPath:filePath contents:nil attributes:nil];

        

        if(result)

        {

            NSLog(@"file create success");

            File* file = new File(relativePath,filePath);

            fileMap[relativePath] = file;

            return file;

        }

        else

            NSLog(@"file create fail");

    }

    else

    {

        if(fileMap.find(relativePath) != fileMap.end())

            return fileMap[relativePath];

        

        File* file = new File(relativePath,filePath);

        fileMap[relativePath] = file;

        return file;

    }

    

    return 0;

}