iOS學(xué)習(xí)之路 文件操作
iOS學(xué)習(xí)之路 文件操作是本文要介紹對內(nèi)容,不多說,直接進入話題。因為應(yīng)用是在沙箱(sandbox)中的,在文件讀寫權(quán)限上受到限制,只能在幾個目錄下讀寫文件:
Documents:應(yīng)用中用戶數(shù)據(jù)可以放在這里,iTunes備份和恢復(fù)的時候會包括此目錄 tmp:存放臨時文件,iTunes不會備份和恢復(fù)此目錄,此目錄下文件可能會在應(yīng)用退出后刪除
Library/Caches:存放緩存文件,iTunes不會備份此目錄,此目錄下文件不會在應(yīng)用退出刪除。
在Documents目錄下創(chuàng)建文件
代碼如下:
- 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登錄設(shè)備看到Documents目錄下生成了該文件。
上述是創(chuàng)建ascii編碼文本文件,如果要帶漢字,比如:
- 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下載到創(chuàng)建的文件打開,中文沒有問題:
在其他目錄下創(chuàng)建文件
如果要指定其他文件目錄,比如Caches目錄,需要更換目錄工廠常量,上面代碼其他的可不變:
- NSArray *paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory
- , NSUserDomainMask
- , YES);
使用NSSearchPathForDirectoriesInDomains只能定位Caches目錄和Documents目錄。
tmp目錄,不能按照上面的做法獲得目錄了,有個函數(shù)可以獲得應(yīng)用的根目錄:
- NSHomeDirectory()
也就是Documents的上級目錄,當然也是tmp目錄的上級目錄。那么文件路徑可以這樣寫:
- NSString *fileName=[NSHomeDirectory() stringByAppendingPathComponent:@"tmp/myFile.txt"];
或者,更直接一點,可以用這個函數(shù):
- NSTemporaryDirectory()
不過生成的路徑將可能是:
- …/tmp/-Tmp-/myFile.txt
使用資源文件
在編寫應(yīng)用項目的時候,常常會使用資源文件,比如:
安裝到設(shè)備上后,是在app目錄下的:
以下代碼演示如何獲取到文件并打印文件內(nèi)容:
- 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);
代碼運行效果:
小結(jié):iOS學(xué)習(xí)之路 文件操作的內(nèi)容介紹完了,希望本文對你有所幫助!
本文編寫時參考了:http://www.servin.com/iphone/iPhone-File-IO.html