天天看點

iPhone 檔案結構和檔案操作iPhone官方SDK用于讀寫臨時資料的方法

ps:請大家加群:ios開發讨論QQ群:73254416,驗證資訊請填寫:CSDN。有什麼問題可以參與交流和讨論。

其實,關于檔案操作,有一個核心的問題,就是你要先搞清楚檔案是存放在哪裡,沙盒,應用程式檔案,還是遠端Url下載下傳類型,如果是圖檔資料還可能是相冊。

不同的存放類型決定了不同的讀取方式和寫入方式。關于存儲類型,請參考另一篇文章:iPhone圖像存儲的幾種類型以及對應的讀取方法。

而本文轉自: http://blog.chinaunix.net/space.php?uid=20622737&do=blog&id=1912783,進行了一下重新編輯和小的修改,與大家共享。

這篇文章主要是針對沙盒存儲方式的檔案操作,詳文如下:

對于一個運作在iPhone得app,它隻能通路自己根目錄下的一些檔案(所謂sandbox).

一個app釋出到iPhone上後,它的目錄結構如下:

iPhone 檔案結構和檔案操作iPhone官方SDK用于讀寫臨時資料的方法

1、其中得 app root 可以用  NSHomeDirectory() 通路到; 2、Documents 目錄就是我們可以用來寫入并儲存檔案得地方,一般可通過:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];
           

得到。

3、tmp 目錄我們可以在裡面寫入一些程式運作時需要用得資料,裡面寫入得資料在程式退出後會沒有。可以通過

NSString *NSTemporaryDirectory(void); 方法得到;

4、檔案一些主要操作可以通過NSFileManage 來操作,可以通過 [NSFileManger defaultManger] 得到它得執行個體。

相關得一些操作:

 a.建立一個目錄或者檔案:

比如要在Documents下面建立一個test目錄,

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSLog(@”%@”,documentsDirectory);

NSFileManager *fileManage = [NSFileManager defaultManager];

NSString *myDirectory = [documentsDirectory stringByAppendingPathComponent:@“test”];

BOOL ok = [fileManage createDirectoryAtPath:myDirectory attributes:nil];
           

比如要在Documents下面建立一個file.txt:

// Result is: /Documents/file1.txt結果為:/Documents/file.txt
NSString *filePath= [documentsDirectory stringByAppendingPathComponent:@"file.txt"];
           

 b.取得一個目錄下得所有檔案名:

//如上面的myDirectory)可用
NSArray *file = [fileManager subpathsOfDirectoryAtPath: myDirectory error:nil];

或

NSArray *files = [fileManager subpathsAtPath: myDirectory ];
           

 c.讀取某個檔案:

NSData *data = [fileManger contentsAtPath:myFilePath];//myFilePath是包含完整路徑的檔案名

或直接用NSData 的類方法:

NSData *data = [NSData dataWithContentOfPath:myFilePath];
           

 d.儲存某個檔案:

//可以用 NSFileManager的下列方法:

- (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSDictionary *)attr;

或 NSData 的

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile;

- (BOOL)writeToFile:(NSString *)path options:(NSUInteger)writeOptionsMask error:(NSError **)errorPtr;
           

  e.删除某個檔案:

//可以用 NSFileManager的下列方法:

//Removes the file or directory at the specified path.
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error

//Removes the file or directory at the specified URL.
- (BOOL)removeItemAtURL:(NSURL *)URL error:(NSError **)error
           

 f.移動某個檔案或者重命名某檔案

想要重命名一個檔案,我們需要把檔案移到一個新的路徑下。下面的代碼建立了我們所期望的目标檔案的路徑,然後請求移動檔案以及在移動之後顯示檔案目錄。
//通過移動該檔案對檔案重命名
NSString *filePath2= [documentsDirectory stringByAppendingPathComponent:@"file2.txt"];
//判斷是否移動
if ([fileManager moveItemAtPath:filePath toPath:filePath2 error:&error] != YES)
NSLog(@"Unable to move file: %@", [error localizedDescription]);
//顯示檔案目錄的内容
NSLog(@"Documentsdirectory: %@",[fileManager contentsOfDirectoryAtPath:documentsDirectoryerror:&error]);
           

 g.計算檔案夾size

-(long)fileSizeForDir:(NSString*)path//計算檔案夾下檔案的總大小
{
    NSFileManager *fileManager = [[NSFileManager alloc] init]; 
    NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];
    for(int i = 0; i<[array count]; i++)
    {
        NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];      
        BOOL isDir;
        if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) )
        {
            NSDictionary *fileAttributeDic=[fileManager attributesOfItemAtPath:fullPatherror:nil];
            size+= fileAttributeDic.fileSize;
        }
        else
        {
            [self fileSizeForDir:fullPath];
        }
    }
    [fileManager release];
    return size;   
}
           

iPhone官方SDK用于讀寫臨時資料的方法

我們知道,出于安全考慮,iPhone的官方SDK并不能像toolchain一樣随意寫檔案。

感謝waza提供的官方SDK用于讀寫臨時資料的方法。

注意:

這兩個方法都是存儲在/Documents/裡面。

bool writeApplicationData(NSData *data, NSString *fileName)
  
{
  
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  
    NSString *documentsDirectory = [paths objectAtIndex:0];
  
    if (!documentsDirectory) {
  
        NSLog(@"Documents directory not found!");
  
        return NO;
  
       }
  
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
 
    return ([data writeToFile:appFile atomically:YES]);
 
}
 
         
 
NSData *applicationDataFromFile(NSString *fileName)
 
{
 
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 
   NSString *documentsDirectory = [paths objectAtIndex:0];
 
   NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
 
   NSData *myData = [[[NSData alloc] initWithContentsOfFile:appFile] autorelease];
 
   return myData;
}