在此篇文章中簡單記錄一下文件管理,在Object C中NSFileManager用於管理文件已經路徑。在Object C中的文件路徑可以是相對路徑也可以是絕對路徑。斜線“/”開頭,斜線實際上就是一個目錄,稱為 根目錄。字符(~)用作用戶主目錄的縮寫。點“ . ”表示當前目錄,兩點“ .. ”表示父目錄。
一. 創建NSFileManager 對象
NSFileManager非常簡單,可以使用如下方式來創建NSFileManager對象。
NSString* fileName=[[NSString alloc] initWithFormat:@"/ISO DeV/File.txt"]; NSFileManager *fileManager=nil; fileManager=[NSFileManager defaultManager];
二. 判斷文件是否存在
使用fileExistsAtPath判斷某個文件是否存在,上面已經所過了,可以使用絕對路徑 也可以使用相對路徑
if([fileManager fileExistsAtPath:fileName]==YES){ NSLog(@"該文件存在"); }else{ NSLog(@"該文件不存在"); }
三. 拷貝文件
使用函數copyPath:(NSString*) toPath(NSString*) 來拷貝一個文件,拷貝文件可以重新命名一個文件名稱
NSString *toFileName=@"/ISO DeV/Test/File1.txt"; NSLog(@"%d",[fileManager fileExistsAtPath:toFileName]); [fileManager copyPath:fileName toPath:toFileName handler:nil]; if([fileManager fileExistsAtPath:toFileName]==YES){ NSLog(@"該文件存在"); }else{ NSLog(@"該文件不存在"); }
四. 判斷文件內容是否相等
if([fileManager contentsEqualAtPath:fileName andPath:toFileName]==YES){ NSLog(@"文件內容相同"); }else{ NSLog(@"文件內容不一樣"); }
五. 重命名文件
NSString *newFileName=@"/ISO DeV/Test/File2.txt"; [fileManager movePath:toFileName toPath:newFileName handler:nil];
六. 獲得文件屬性
NSDictionary *dic= [fileManager fileAttributesAtPath:newFileName traverseLink:NO]; for (NSString *key in[dic keyEnumerator]) { NSLog(@"====== %@=%@",key,[dic valueForKey:key]); }
使用方法fileAttributesAtPath 獲得某個路徑下的文件的屬性,返回值是一個NSDictionary. 以上代碼輸出得到如下:
2014-05-02 23:24:23.993 PIOFile[537:303] ====== NSFileOwnerAccountID=501 2014-05-02 23:24:23.993 PIOFile[537:303] ====== NSFileHFSTypeCode=0 2014-05-02 23:24:23.993 PIOFile[537:303] ====== NSFileSystemFileNumber=18447915 2014-05-02 23:24:23.994 PIOFile[537:303] ====== NSFileExtensionHidden=0 2014-05-02 23:24:23.994 PIOFile[537:303] ====== NSFileSystemNumber=16777219 2014-05-02 23:24:23.995 PIOFile[537:303] ====== NSFileSize=38 2014-05-02 23:24:23.995 PIOFile[537:303] ====== NSFileGroupOwnerAccountID=0 2014-05-02 23:24:23.995 PIOFile[537:303] ====== NSFileOwnerAccountName=hechen 2014-05-02 23:24:23.997 PIOFile[537:303] ====== NSFileCreationDate=2014-05-02 14:48:12 +0000 2014-05-02 23:24:23.997 PIOFile[537:303] ====== NSFilePosixPermissions=420 2014-05-02 23:24:23.997 PIOFile[537:303] ====== NSFileHFSCreatorCode=0 2014-05-02 23:24:23.998 PIOFile[537:303] ====== NSFileType=NSFileTypeRegular 2014-05-02 23:24:23.998 PIOFile[537:303] ====== NSFileExtendedAttributes={ "com.apple.TextEncoding" = <7574662d 383b3133 34323137 393834>; } 2014-05-02 23:24:23.999 PIOFile[537:303] ====== NSFileGroupOwnerAccountName=wheel 2014-05-02 23:24:23.999 PIOFile[537:303] ====== NSFileReferenceCount=1 2014-05-02 23:24:24.000 PIOFile[537:303] ====== NSFileModificationDate=2014-05-02 15:12:27 +0000
七. 刪除文件
[fileManager removeFileAtPath:newFileName handler:nil];
通過方法removeFileAtPath 可以刪除文件
八. 獲取文件內容
NSString *content=[NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:nil]; NSLog(@"%@",content);
