iOS 文件管理

一、iOS中的沙盒機制

iOS應用程序只能對自己創建的文件系統讀取文件,這個獨立、封閉、安全的空間,叫做沙盒。它一般存放著程序包文件(可執行文件)、圖片、音頻、視頻、plist文件、sqlite數據庫以及其他文件。

每個應用程序都有自己的獨立的存儲空間(沙盒)

一般來說應用程序之間是不可以互相訪問

模擬器沙盒的位置:

/User/userName/Library/Application Support/iPhone Simulator

當我們創建應用程序時,在每個沙盒中含有三個文件,分別是Document、Library和temp。

Document:一般需要持久的數據都放在此目錄中,可以在當中添加子文件夾,iTunes備份和恢復的時候,會包括此目錄。

Library:設置程序的默認設置和其他狀態信息

temp:創建臨時文件的目錄,當iOS設備重啟時,文件會被自動清除

獲取沙盒目錄

// 獲取沙盒根目錄路徑

NSString*homeDir = NSHomeDirectory();

// 獲取Documents目錄路徑

NSString*docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject];

//獲取Library的目錄路徑

NSString*libDir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES) lastObject];

// 獲取cache目錄路徑(/Library/Caches)

NSString*cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) firstObject];

// 獲取tmp目錄路徑

NSString*tmpDir =NSTemporaryDirectory();

// 獲取應用程序程序包中資源文件路徑的方法:

NSLog(@"%@",[[NSBundle mainBundle] bundlePath]);

NSString*imagePath = [[NSBundle mainBundle] pathForResource:@"apple"ofType:@"png"];

UIImage*appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath];

二、NSString類路徑的處理方法

文件路徑的處理

NSString *path?=?@"/Uesrs/apple/testfile.txt"

常用方法如下

獲得組成此路徑的各個組成部分,結果:("/","User","apple","testfile.txt")

-?(NSArray *)pathComponents;

提取路徑的最后一個組成部分,結果:testfile.txt

-?(NSString?*)lastPathComponent;

刪除路徑的最后一個組成部分,結果:/Users/apple

-?(NSString *)stringByDeletingLastPathCpmponent;

將app.txt添加到path路徑的末尾,結果:/Users/apple/testfile.txt/app.txt

- (NSString *)stringByAppendingPathComponent:(NSString *)str;

去路徑最后部分的擴展名,結果:text

-?(NSString?*)pathExtension;

刪除路徑最后部分的擴展名,結果:/Users/apple/testfile

-?(NSString?*)stringByDeletingPathExtension;

路徑最后部分追加擴展名,結果:/User/apple/testfile.txt.jpg

-?(NSString?*)stringByAppendingPathExtension:(NSString?*)str;

三、NSData

NSData是用來包裝數據的

NSData存儲的是二進制數據,屏蔽了數據之間的差異,文本、音頻、圖像等數據都可用NSData來存儲

NSData的用法

1.NSString與NSData互相轉換

NSData-> NSString ?????????????????????????????????????????????????????????????????????????????????

NSString *aString?=?[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSString->NSData ??????????????????????????????????????????????????????????????????????????????????

NSString *aString?=?@"1234abcd";

NSData *aData?=?[aString dataUsingEncoding: NSUTF8StringEncoding];

將data類型的數據,轉成UTF8的數據

+(NSString *)dataToUTF8String:(NSData?*)data

{

NSString *buf?=?[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

return [buf autorelease];

}

將string轉換為指定編碼

+(NSString *)changeDataToEncodinString:(NSData?*)data encodin:(NSStringEncoding )encodin

{

NSString *buf?=?[[[NSString alloc] initWithData:data encoding:encodin] autorelease];

return buf;

}

2. NSData 與 UIImage

NSData->UIImage

UIImage *aimage?=?[UIImage imageWithData: imageData];

//例:從本地文件沙盒中取圖片并轉換為NSData

NSString *path?=?[[NSBundle mainBundle] bundlePath];

NSString *name?=?[NSString stringWithFormat:@"ceshi.png"];

NSString *finalPath?=?[path stringByAppendingPathComponent:name];

NSData *imageData?=?[NSData dataWithContentsOfFile: finalPath];

UIImage *aimage?=?[UIImage imageWithData: imageData];

3.NSData與NSArray? NSDictionary

+(NSString *)getLocalFilePath:(NSString?*) fileName

{

return [NSString stringWithFormat:@"%@/%@%@", NSHomeDirectory(),@“Documents”,fileName];

}

包括將NSData寫進Documents目錄

從Documents目錄讀取數據

在進行網絡數據通信的時候,經常會遇到NSData類型的數據。在該數據是dictionary結構的情況下,系統沒有提供現成的轉換成NSDictionary的方法,為此可以通過Category對NSDictionary進行擴展,以支持從NSData到NSDictionary的轉換。聲明和實現如下:

+?(NSDictionary *)dictionaryWithContentsOfData:(NSData?*)data?{

CFPropertyListRef list = CFPropertyListCreateFromXMLData(kCFAllocatorDefault,?(CFDataRef)data, kCFPropertyListImmutable, NULL);

if(list == nil) return nil;

if ([(id)list isKindOfClass:[NSDictionary class]])?{

return [(NSDictionary?*)list autorelease];

}else {

CFRelease(list);

return nil;

}

}

四、文件管理常用方法

NSFileManager

創建一個文件并寫入數據

-?(BOOL)createFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSDictionary *)attr;

從一個文件中讀取數據

-?(NSData?*)contentsAtPath:(NSString?*)path;

scrPath路徑上的文件移動到dstPath路徑上,注意這里的路徑是文件路徑而不是目錄

-?(BOOL)moveItemAtPath:(NSString?*)srcPath toPath:(NSString *)dstPath error:(NSError **) error;

scrPath路徑上的文件復制到dstPath路徑上

-?(BOOL)copyItemAtPath:(NSString *)scrPath toPath:(NSString *)dstPath error:(NSError **) error;

比較兩個文件的內容是否一樣

-?(BOOL)contentsEqualAtPath:(NSString *)path1 andPath:(NSString *)path2;

文件是否存在

-?(BOOL)fileExistsAtPath:(NSString?*)path;

移除文件

-?(BOOL)removeItemAtPath:(NSString?*)path error:(NSError **) error;

創建文件管理

NSFileManager *fileManager?=?[NSFileManager defaultManager]; ? ?

NSString *path?=?[NSHomeDirectory(?)? stringByAppendingPathComponent:@"holyBible.txt"];???????????????????????????????????????????????????????????????????????????????????????????????????? NSString *text?=?@"abcdefg";

將字符串轉成NSData類型

NSData *data?=?[text dataUsingEncoding: NSUTF8StringEncoding];

寫入文件

BOOL success =?[fileManager createFileAtPath:path contents:data attributes:nil];

創建文件并寫入

NSString *filePath?=?[path stringByAppendingPathComponent:@"holyBible.txt"];?????

NSString *contect?=?@"abcdefg";????????????????????????????????????????????????????????????????

BOOL success = [fileManager createFileAtPath:filePath contents:[contect dataUsingEncoding: NSUTF8StringEncoding] attributes:nil];

NSFileManager-讀取內容

NSData *fileData?=?[fileManager contentsAtPath:filePath];??????????????????????????????????

NSString *content?=?[[NSString alloc] initWithData:fileData dataUsingEncoding: NSUTF8StringEncoding];

NSData-讀取內容

NSString *filePath?=?[path stringByAppendingPathComponent:@"holyBible.txt"];?????

NSData *data?=?[NSData dataWithContentOfFile:filePath];

NSString-讀取內容

NSString *filePath?=?[path stringByAppendingPathComponent:@"holyBible.txt"];?????

NSString *content?=?[[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

// 創建一個新目錄

- (BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(nullable NSDictionary*)attributes error:(NSError **)error;

// 1、創建多級目錄的文件時,要先判斷其目錄是否存在,如果不存在就創建該目錄,如果沒有創建該目錄,文件是不能創建成功的

// 2、記得將createIntermediates設置為YES,這樣就能建立多級目錄了。如果是一級目錄,可以設置為NO。

// 3、stringByDeletingLastPathComponent是關鍵,代表-->刪除路徑中的最后一個組成部分.

[fileManager createDirectoryAtPath:[path stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];

創建一個新目錄的例子:

// 獲取Documents目錄路徑

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject];

NSString *directryPath = [docPath stringByAppendingPathComponent:@"目錄文件夾"];

NSFileManager *fileManager = [NSFileManager defaultManager];

// 創建一個新目錄

// 1、創建多級目錄的文件時,要先判斷其目錄是否存在,如果不存在就創建該目錄,如果沒有創建該目錄,文件是不能創建成功的

// 2、記得將createIntermediates設置為YES,這樣就能建立多級目錄了。如果是一級目錄,可以設置為NO。

[fileManager createDirectoryAtPath:directryPath withIntermediateDirectories:YES attributes:nil error:nil];

NSString *finalPath = [directryPath stringByAppendingPathComponent:@"文件名稱"];

[fileManager createFileAtPath:finalPath contents:nil attributes:nil];

移動、復制文件

移動文件(重命名)

NSString *toPath?=?[NSHomeDirectory(?) stringByAppendingPathComponent:@"hellogod/New Testament.txt"]; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

[fileManager createDirectoryAtPath:[toPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil]; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

?NSError *error;???????????????????????????????????????????????????????????????????????????????????????

?BOOL isSuccess =?[fm moveItemAtPath:filePath toPath:toPath error:&error];

復制文件(重命名)

NSString *copyPath?=?[NSHomeDirectory(?) stringByAppendingPathComponent:@"備份/Old Testament.txt"];

[fileManager createDirectoryAtPath:[toPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil]; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

BOOL success = [fm copyItemAtPath:toPath toPath:toPath error:nil];

刪除文件、獲取文件大小

判斷文件是否存在和刪除文件

if( [fileManager fileExistsAtPath:copyPath] )? {? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

? ? ? ? if ( [ [fileManager removeItemAtPath:copyPath ] error:nil ] )? {? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

? ? ? ? ? ? ? ? ? ?NSLog(@"remove success");? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

? }

獲取文件大小

NSFileManager *fileManager?=?[NSFileManager defaultManager]; ? ? ? ? ? ? ? ??

獲得文件的屬性字典 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

NSDictionary *attrDic?=?[fileManager attributesOfItemAtpath:sourcePath error:nil];?

NSNumber *fileSize?=?[attrDic objectForKey:NSFileSize];

獲取目錄文件信息

NSFileManager *fileManager?=?[NSFileManager defaultManager];????????????????????????

NSString *enuPath?=?[NSHomeDirectoty(?) stringByAppendingPathComponent:@"Test"];?????????????????????????????????????????????????????????????????????????????????????????????????????????? NSDictionaryEnumerator *dirEnum?=?[fileManager enumeratorAtPath:enuPath];????

NSString *path?= nil;????????????????????????????????????????????????????????????????????????????????????

while ((path?=?[dirEnum nextObject]}?!= nil) ?{ ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? NSLog(@"%@",path);????????????????????????????????????????????????????????????????????????????????????????

}

參考鏈接:

iOS開發-文件管理(一)

沙盒和NSBundle

ios NSFileManager創建目錄、文件

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,572評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,071評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,409評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,569評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,360評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,895評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,979評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,123評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,643評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,559評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,742評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,250評論 5 356
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,981評論 3 346
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,363評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,622評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,354評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,707評論 2 370

推薦閱讀更多精彩內容

  • 一、iOS中的沙盒機制 iOS應用程序只能對自己創建的文件系統讀取文件,這個獨立、封閉、安全的空間,叫做沙盒。它一...
    tzhtodd閱讀 1,290評論 0 2
  • iOS開發-文件管理(一) 一、iOS中的沙盒機制 iOS應用程序只能對自己創建的文件系統讀取文件,這個獨立、封閉...
    MacShare閱讀 1,809評論 0 6
  • 一、iOS中的沙盒機制 ?iOS應用程序只能對自己創建的文件系統讀取文件,這個獨立、封閉、安全的空間,叫做沙盒。它...
    舒城8中閱讀 2,398評論 0 6
  • 一、iOS中的沙盒機制 iOS應用程序只能對自己創建的文件系統讀取文件,這個獨立、封閉、安全的空間,叫做沙盒。它一...
    1d5cb7cff98d閱讀 1,783評論 0 0
  • 文件操作 NSFileManager 1.NSFileManager 專門負責文件/文件夾的管理操作,包括創建/刪...
    Jackjun閱讀 2,066評論 0 1