天天看點

NSFileManager 檔案相關操作

得到Document目錄:

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

得到temp臨時目錄:

NSString *tempPath = NSTemporaryDirectory();
           

得到目錄上的檔案位址:

NSString *檔案位址 = [目錄位址 stringByAppendingPathComponent:@"檔案名.擴充名"];
           

NSFileManager

用于執行一般的檔案系統操作 (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:  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來建立檔案。

轉載:http://hi.baidu.com/lrorolove/blog/item/578afff57eac83c4f3d3857b.html