iOS中對檔案的操作

來源:互聯網
上載者:User

標籤:

轉自:http://marshal.easymorse.com/archives/3340iOS中對檔案的操作

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

  • Documents:應用中使用者資料可以放在這裡,iTunes備份和恢複的時候會包括此目錄
  • tmp:存放臨時檔案,iTunes不會備份和恢複此目錄,此目錄下檔案可能會在應用退出後刪除
  • Library/Caches:存放快取檔案,iTunes不會備份此目錄,此目錄下檔案不會在應用退出刪除
在Documents目錄下建立檔案

代碼如下:

NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory
                                            , NSUserDomainMask 
                                            , YES); 
NSLog(@"Get document path: %@",[paths objectAtIndex:0]);

NSString *fileName=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"myFile"]; 
NSString *[email protected]"a"; 
NSData *contentData=[content dataUsingEncoding:NSASCIIStringEncoding]; 
if ([contentData writeToFile:fileName atomically:YES]) {
    NSLog(@">>write ok."); 
}

可以通過ssh登入裝置看到Documents目錄下產生了該檔案。

 

上述是建立ascii編碼文字檔,如果要帶漢字,比如:

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

如果還用ascii編碼,將不會組建檔案。這裡使用NSUnicodeStringEncoding就可以了。

通過filezilla下載到建立的檔案開啟,中文沒有問題:

在其他目錄下建立檔案

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

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

 

使用NSSearchPathForDirectoriesInDomains只能定位Caches目錄和Documents目錄。

tmp目錄,不能按照上面的做法獲得目錄了,有個函數可以獲得應用的根目錄:

NSHomeDirectory()

也就是Documents的上級目錄,當然也是tmp目錄的上級目錄。那麼檔案路徑可以這樣寫:

NSString *fileName=[NSHomeDirectory() stringByAppendingPathComponent:@"tmp/myFile.txt"];

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

NSTemporaryDirectory()

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

…/tmp/-Tmp-/myFile.txt

使用資源檔

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

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

以下代碼示範如何擷取到檔案並列印檔案內容:

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);

 

代碼運行效果:

 

iOS檔案系統的管理  NSFileManager 判斷一個給定路勁是否為檔案夾

[self.fileManagerfileExistsAtPath:isDirectory:];

用於執行一般的檔案系統操作 (reading and writing is done via NSData, et. al.).
主要功能包括:從一個檔案中讀取資料;向一個檔案中寫入資料;刪除檔案;複製檔案;移動檔案;比較兩個檔案的內容;測試檔案的存在性;讀取/變更檔的屬性... ... 
Just alloc/init an instance and start performing operations. Thread safe.

  • 常見的NSFileManager處理檔案的方法如下:
NSFileManager *fileManager = [[NSFileManager alloc]init]; //最好不要用defaultManager。 
NSData *myData = [fileManager contentsAtPath:path]; // 從一個檔案中讀取資料 
[fileManager createFileAtPath:path contents:myData attributes:dict];//向一個檔案中寫入資料,屬性字典允許你制定要建立 
[fileManager removeItemAtPath:path error:err]; 
[fileManager moveItemAtPath:path toPath:path2 error:err]; 
[fileManager copyItemAtPath:path toPath:path2 error:err]; 
[fileManager contentsEqualAtPath:path andPath:path2]; 
[fileManager fileExistsAtPath:path]; ... ...
  • 常見的NSFileManager處理目錄的方法如下:
[fileManager currentDirectoryPath]; 
[fileManager changeCurrentDirectoryPath:path]; 
[fileManager copyItemAtPath:path toPath:path2 error:err]; 
[fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:err]; 
[fileManager fileExistsAtPath:path isDirectory:YES]; 
[fileManager enumeratorAtPath:path]; //擷取目錄的內容列表。一次可以枚舉指定目錄中的每個檔案。 ... ...
Has a delegate with lots of “should” methods (to do an operation or proceed after an error).
And plenty more. Check out the documentation.

1、檔案的建立

-(IBAction) CreateFile

{

//對於錯誤資訊

NSError *error;

// 建立檔案管理工具

NSFileManager *fileMgr = [NSFileManager defaultManager];

//指向檔案目錄

NSString *documentsDirectory= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];


//建立一個目錄

[[NSFileManager defaultManager]   createDirectoryAtPath: [NSString stringWithFormat:@"%@/myFolder", NSHomeDirectory()] attributes:nil];

// File we want to create in the documents directory我們想要建立的檔案將會出現在檔案目錄中

// Result is: /Documents/file1.txt結果為:/Documents/file1.txt

NSString *filePath= [documentsDirectory

stringByAppendingPathComponent:@"file2.txt"];

//需要寫入的字串

NSString *str= @"iPhoneDeveloper Tips\nhttp://iPhoneDevelopTips,com";

//寫入檔案

[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

//顯示檔案目錄的內容

NSLog(@"Documentsdirectory: %@",[fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
}

 

 

2、對檔案重新命名

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

 

3、刪除一個檔案


為了使這個技巧完整,讓我們再一起看下如何刪除一個檔案:
//在filePath2中判斷是否刪除這個檔案
if ([fileMgr removeItemAtPath:filePath2 error:&error] != YES)
NSLog(@"Unable to delete file: %@", [error localizedDescription]);
//顯示檔案目錄的內容
NSLog(@"Documentsdirectory: %@",
[fileMgr contentsOfDirectoryAtPath:documentsDirectoryerror:&error]);
一旦檔案被刪除了,正如你所預料的那樣,檔案目錄就會被自動清空:

這些樣本能教你的,僅僅只是檔案處理上的一些皮毛。想要獲得更全面、詳細的講解,你就需要掌握NSFileManager檔案的知識。

 

 

4、刪除目錄下所有檔案

//擷取檔案路徑
- (NSString *)attchmentFolder{

NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *path = [document stringByAppendingPathComponent:@"Attchments"];


NSFileManager *manager = [NSFileManager defaultManager];


if(![manager contentsOfDirectoryAtPath:path error:nil]){

[manager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];

}
return path;

}

--清除附件
BOOL result = [[NSFileManager defaultManager] removeItemAtPath:[[MOPAppDelegate instance] attchmentFolder] error:nil];

5、判斷檔案是否存在

NSString *filePath = [self dataFilePath];

if ([[NSFileManager defaultManager]fileExistsAtPath:filePath]) 

  //do some thing

附:

 

-(NSString *)dataFilePath

{

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

NSString *documentDirectory = [paths objectAtIndex:0];

return [documentDirectory stringByAppendingPathComponent:@"data.plist"];

}

 


常用路徑工具函數NSString * NSUserName(); 返回目前使用者的登入名稱 NSString * NSFullUserName(); 返回目前使用者的完整使用者名稱 NSString * NSHomeDirectory(); 返回目前使用者主目錄的路徑 NSString * NSHomeDirectoryForUser(); 返回使用者user的主目錄 NSString * NSTemporaryDirectory(); 返回可用於建立臨時檔案的路徑目錄   常用路徑工具方法-(NSString *) pathWithComponents:components    根據components(NSArray對象)中元素構造有效路徑 -(NSArray *)pathComponents                                          析構路徑,擷取路徑的各個部分 -(NSString *)lastPathComponent                                       提取路徑的最後一個組成部分 -(NSString *)pathExtension                                           路徑副檔名 -(NSString *)stringByAppendingPathComponent:path                    將path添加到現有路徑末尾 -(NSString *)stringByAppendingPathExtension:ext           將拓展名添加的路徑最後一個組成部分 -(NSString *)stringByDeletingPathComponent                           刪除路徑的最後一個部分 -(NSString *)stringByDeletingPathExtension                           刪除路徑的最後一個部分 的副檔名 -(NSString *)stringByExpandingTildeInPath          將路徑中的代字元擴充成使用者主目錄(~)或指定使用者主目錄(~user) -(NSString *)stringByResolvingSymlinksInPath                         嘗試解析路徑中的符號連結 -(NSString *)stringByStandardizingPath            通過嘗試解析~、..、.、和符號連結來標準化路徑 -  使用路徑NSPathUtilities.h tempdir = NSTemporaryDirectory(); 臨時檔案的目錄名 path = [fm currentDirectoryPath];[path lastPathComponent]; 從路徑中提取最後一個檔案名稱 fullpath = [path stringByAppendingPathComponent:fname];將檔案名稱附加到路勁的末尾 extenson = [fullpath pathExtension]; 路徑名的副檔名 homedir = NSHomeDirectory();使用者的主目錄 component = [homedir pathComponents];  路徑的每個部分   NSProcessInfo類:允許你設定或檢索正在啟動並執行應用程式的各種類型資訊(NSProcessInfo *)processInfo                                  返回當前進程的資訊-(NSArray*)arguments                                           以NSString對象數位形式返回當前進程的參數-(NSDictionary *)environment                                   返回變數/值對詞典。描述當前的環境變數-(int)processIdentity                                          返回進程標識-(NSString *)processName                                       返回進程名稱-(NSString *)globallyUniqueString   每次調用該方法都會返回不同的單值字串,可以用這個字串產生單值臨時檔案名稱   -(NSString *)hostname                                          返回主機系統的名稱 -(unsigned int)operatingSystem                                 返回表示作業系統的數字 -(NSString *)operatingSystemName                                     返回作業系統名稱 -(NSString *)operatingSystemVersionString                                     返回作業系統目前的版本-(void)setProcessName:(NSString *)name                                將當前進程名稱設定為name 

============================================================================
  NSFileHandle類允許更有效地使用檔案。
可以實現如下 功能
1、開啟一個檔案,執行讀、寫或更新(讀寫)操作;
2、在檔案中尋找指定位置;
3、從檔案中讀取特定數目的位元組,或將特定數目的位元組寫入檔案中
另外,NSFileHandle類提供的方法也可以用於各種裝置或通訊端。一般而言,我們處理檔案時都要經曆以下三個 步驟
1、開啟檔案,擷取一個NSFileHandle對象(以便在後面的I/O操作中引用該檔案)。
2、對開啟檔案執行I/O操作。
3、關閉檔案。
NSFileHandle *fileHandle = [[NSFileHandle alloc]init]; 
fileHandle = [NSFileHandle fileHandleForReadingAtPath:path]; //開啟一個檔案準備讀取
fileHandle = [NSFileHandle fileHandleForWritingAtPath:path]; 
fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:path]; 
fileData = [fileHandle availableData]; // 從裝置或者通道返回可用的資料 
fileData = [fileHandle readDataToEndOfFile]; 
[fileHandle writeData:fileData]; //將NSData資料寫入檔案 
[fileHandle closeFile]; //關閉檔案 ... ...
註:NSFileHandle類沒有提供建立檔案的功能,所以必須使用NSFileManager來建立檔案

iOS中對檔案的操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.