iOS中對文件的操作

iOS中對文件的操作

來自  Fgamers
838 次閱讀 評論 (1)

因爲應用是在沙箱(sandbox)中的,在文件讀寫權限上受到限制,只能在幾個目錄下讀寫文件:

  • Documents:應用中用戶數據可以放在這裏,iTunes備份和恢復的時候會包括此目錄
  • tmp:存放臨時文件,iTunes不會備份和恢復此目錄,此目錄下文件可能會在應用退出後刪除
  • Library/Caches:存放緩存文件,iTunes不會備份此目錄,此目錄下文件不會在應用退出刪除

在Documents目錄下創建文件

代碼如下:

1
2
3
4
5
6
7
8
9
10
11
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory
                                                , NSUserDomainMask
                                                , YES);
    NSLog(@"Get document path: %@",[paths objectAtIndex:0]);
 
    NSString *fileName=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"myFile"];
    NSString *content=@"a";
    NSData *contentData=[content dataUsingEncoding:NSASCIIStringEncoding];
    if ([contentData writeToFile:fileName atomically:YES]) {
        NSLog(@">>write ok.");
    }

可以通過ssh登錄設備看到Documents目錄下生成了該文件。

上述是創建ascii編碼文本文件,如果要帶漢字,比如:

1
2
3
4
5
6
NSString *fileName=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"myFile"];
NSString *content=@"更深夜靜人已息";
NSData *contentData=[content dataUsingEncoding:NSUnicodeStringEncoding];
if ([contentData writeToFile:fileName atomically:YES]) {
    NSLog(@">>write ok.");
}

如果還用ascii編碼,將不會生成文件。這裏使用NSUnicodeStringEncoding就可以了。

通過filezilla下載到創建的文件打開,中文沒有問題:

在其他目錄下創建文件

如果要指定其他文件目錄,比如Caches目錄,需要更換目錄工廠常量,上面代碼其他的可不變:

<pre lang="objc" line="1”>NSArray *paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory , NSUserDomainMask , YES);</pre><p>使用NSSearchPathForDirectoriesInDomains只能定位Caches目錄和Documents目錄。</p><p>tmp目錄,不能按照上面的做法獲得目錄了,有個函數可以獲得應用的根目錄:</p><pre>NSHomeDirectory()</pre><p>也就是Documents的上級目錄,當然也是tmp目錄的上級目錄。那麼文件路徑可以這樣寫:</p><div class=" wp_syntax"="" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-width: initial; border-color: initial; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; border-image: initial; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; ">
1
NSString *fileName=[NSHomeDirectory() stringByAppendingPathComponent:@"tmp/myFile.txt"];

或者,更直接一點,可以用這個函數:

NSTemporaryDirectory() 

不過生成的路徑將可能是:

…/tmp/-Tmp-/myFile.txt

使用資源文件

在編寫應用項目的時候,常常會使用資源文件,比如:

安裝到設備上後,是在app目錄下的:

以下代碼演示如何獲取到文件並打印文件內容:

1
2
3
4
5
NSString *myFilePath = [[NSBundle mainBundle]
                        pathForResource:@"f"
                        ofType:@"txt"];
NSString *myFileContent=[NSString stringWithContentsOfFile:myFilePath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"bundel file path: %@ \nfile content: %@",myFilePath,myFileContent);

代碼運行效果:

原文鏈接:http://marshal.easymorse.com/archives/3340

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章