您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 基礎知識 >> iOS 入門介紹

iOS 檔案處理:常用 NSFileManager 操作整理

編輯:iOS 入門介紹

iOS 檔案處理


簡介

檔案處理很難單靠文字描述理解,直接看程式碼會清楚得多。

由於 iOS 的應用程式運行在沙盒(sandbox)環境中,檔案讀寫權限受到嚴格限制,只能在少數幾個指定目錄底下作業。

常用方法

以下列出操作檔案的常用方法。使用前請將 FilePath1、FilePath 等字串替換為完整的檔案路徑。

檢查檔案是否存在

 NSFileManager *fileManager = [NSFileManager defaultManager]; //Get documents directory NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0]; if ([fileManager fileExistsAtPath:@""]==YES) { NSLog(@"File exists"); } 

比較兩個檔案的內容

 if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) { NSLog(@"Same content"); } 

檢查是否可寫、可讀、可執行

 if ([fileManager isWritableFileAtPath:@"FilePath"]) { NSLog(@"isWritable"); } if ([fileManager isReadableFileAtPath:@"FilePath"]) { NSLog(@"isReadable"); } if ( [fileManager isExecutableFileAtPath:@"FilePath"]){ NSLog(@"is Executable"); } 

移動檔案

 if([fileManager moveItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]){ NSLog(@"Moved successfully"); } 

複製檔案

 if ([fileManager copyItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]) { NSLog(@"Copied successfully"); } 

刪除檔案

 if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) { NSLog(@"Removed successfully"); } 

讀取檔案

 NSData *data = [fileManager contentsAtPath:@"Path"]; 

寫入檔案

 [fileManager createFileAtPath:@"" contents:data attributes:nil]; 

實務建議:正式環境中請勿將 error 參數傳為 NULL,改傳入 NSError 物件並記錄訊息,才能有效追蹤失敗原因。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved