iOS文件操作

一、獲取沙盒下文件目錄

沙盒應用根目錄:NSHomeDirectory()是應用程序目錄的路徑,在改文件目錄下有三個文件夾:Documents、Library、temp以及一個.app包

NSString *homeDir = NSHomeDirectory();

應用程序包:存放應用程序的源文件播急,包括資源文件和可執(zhí)行文件

[[NSBundle mainBundle] pathForResource:@"wtdb" ofType:@"sqlite"];

Documents:保存用戶生成的文件、應用程序不能重新創(chuàng)建的文件售睹∽可被iTunes備份

// 獲取Documents目錄路徑
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

Library:可創(chuàng)建子文件夾。除Caches以外昌妹,都會被iTunes備份
/Preferences:包含應用程序的偏好設置文件
/Caches:用于存放應用程序專用的支持文件捶枢,保存應用程序再次啟動過程中需要的信息握截,保存可以重新下載或者重新生成的數據。適合存儲體積大烂叔,不需要備份的非重要數據

// 獲取Library的目錄路徑
NSString *libDir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];

// 獲取Caches目錄路徑
NSString *cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];

tmp:存放臨時數據谨胞,保存應用程序再次啟動過程中不需要的信息。不會被iTunes備份

// 獲取tmp目錄路徑
NSString *tmpDir =  NSTemporaryDirectory();

關于iOS Data Storage Guidelines蒜鸡,參考iOS Data Storage Guidelines - Apple Developer

  • Documents和Caches文件夾區(qū)別

    如果你做個記事本的app胯努,那么用戶寫了東西,總要把東西存起來逢防。那么這個文件則是用戶自行生成的叶沛,就放在documents文件夾里面。
    如果需要和服務器配合忘朝,經常從服務器下載東西灰署,展示給用戶看。那么這些下載下來的東西就放在library/caches局嘁。

二溉箕、文件夾操作

創(chuàng)建文件夾

NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//test文件夾
documentsDir = [documentsDir stringByAppendingPathComponent:@"test"];
//是否是文件夾
BOOL isDir;
BOOL isExit = [filemanager fileExistsAtPath:documentsDir isDirectory:&isDir];
//文件夾是否存在
if (!isExit || !isDir) {
    [filemanager createDirectoryAtPath:documentsDir withIntermediateDirectories:YES attributes:nil error:nil];
}

刪除文件夾

//刪除Wtdb文件夾
NSString *cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
NSString *wtdbPath = [cachesDir stringByAppendingPathComponent:@"Wtdb"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:wtdbPath]) {
    BOOL isSuccess = [fileManager removeItemAtPath:wtdbPath error:nil];
}

移動文件夾

NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
NSString *moveToPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
BOOL isSuccess = [fileManager moveItemAtPath:filePath toPath:moveToPath error:nil];
if (isSuccess) {
    NSLog(@"rename success");
}else{
    NSLog(@"rename fail");
}

重命名文件夾

//通過移動該文件對文件重命名
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
NSString *moveToPath = [documentsPath stringByAppendingPathComponent:@"rename.txt"];
BOOL isSuccess = [fileManager moveItemAtPath:filePath toPath:moveToPath error:nil];
if (isSuccess) {
    NSLog(@"rename success");
}else{
    NSLog(@"rename fail");
}

三、文件操作

復制

//bundle里的數據庫文件復制到Caches/Wtdb文件夾下
NSString *cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
NSFileManager *filemanager = [NSFileManager defaultManager];
cachesDir = [cachesDir stringByAppendingPathComponent:@"Wtdb"];
BOOL isDir;//是否是文件夾
BOOL exit = [filemanager fileExistsAtPath:cachesDir isDirectory:&isDir];
//文件夾是否存在
if (!exit || !isDir) {
    [filemanager createDirectoryAtPath:cachesDir withIntermediateDirectories:YES attributes:nil error:nil];
}
//判斷數據庫文件是否存在
NSString *wtdbPath = [cachesDir stringByAppendingPathComponent:@"wtdb.sqlite"];
//如果文件不存在悦昵,則復制
if (![filemanager fileExistsAtPath:wtdbPath]) {
    NSString *dbBundlePath = [[NSBundle mainBundle] pathForResource:@"wtdb" ofType:@"sqlite"];
    BOOL isSuccess = [filemanager copyItemAtPath:dbBundlePath toPath:wtdbPath error:nil];
    DLog(@"數據庫文件%@", isSuccess ? @"拷貝成功" : @"拷貝失敗");
}
  • 刪除肴茄、移動、重命名與文件夾操作類似旱捧,path為文件路徑独郎。

寫數據到文件

NSString *documentsPath =[self dirDoc];  
NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];  
NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];  
NSString *content=@"測試寫入內容!";  
BOOL res=[content writeToFile:testPath atomically:YES encoding:NSUTF8StringEncoding error:nil];  
if (res) {  
    NSLog(@"文件寫入成功");  
}else {  
    NSLog(@"文件寫入失敗");  
}

讀文件數據

NSString *documentsPath =[self dirDoc];  
NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];  
NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];  
//NSData *data = [NSData dataWithContentsOfFile:testPath];  
//NSLog(@"文件讀取成功: %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);  
NSString *content=[NSString stringWithContentsOfFile:testPath encoding:NSUTF8StringEncoding error:nil];  
NSLog(@"文件讀取成功: %@",content);  

文件屬性

NSString *documentsPath =[self dirDoc];  
NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];  
NSFileManager *fileManager = [NSFileManager defaultManager];  
NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];  
NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:testPath error:nil];     
NSArray *keys;  
id key, value;  
keys = [fileAttributes allKeys];  
int count = [keys count];  
for (int i = 0; i < count; i++)  
{  
    key = [keys objectAtIndex: i];  
    value = [fileAttributes objectForKey: key];  
    NSLog (@"Key: %@ for value: %@", key, value);  
} 

參考:

  1. http://www.cnblogs.com/iOS-mt/p/4185407.html
  2. http://www.superqq.com/blog/2015/07/24/nsfilemanagerwen-jian-cao-zuo-de-shi-ge-xiao-gong-neng/
  3. http://www.itdadao.com/articles/c15a663369p0.html
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末枚赡,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子谓谦,更是在濱河造成了極大的恐慌贫橙,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,542評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件反粥,死亡現場離奇詭異卢肃,居然都是意外死亡,警方通過查閱死者的電腦和手機才顿,發(fā)現死者居然都...
    沈念sama閱讀 92,822評論 3 394
  • 文/潘曉璐 我一進店門莫湘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人郑气,你說我怎么就攤上這事幅垮。” “怎么了尾组?”我有些...
    開封第一講書人閱讀 163,912評論 0 354
  • 文/不壞的土叔 我叫張陵忙芒,是天一觀的道長示弓。 經常有香客問我,道長呵萨,這世上最難降的妖魔是什么奏属? 我笑而不...
    開封第一講書人閱讀 58,449評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮潮峦,結果婚禮上囱皿,老公的妹妹穿的比我還像新娘。我一直安慰自己忱嘹,他們只是感情好嘱腥,可當我...
    茶點故事閱讀 67,500評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著德谅,像睡著了一般爹橱。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上窄做,一...
    開封第一講書人閱讀 51,370評論 1 302
  • 那天愧驱,我揣著相機與錄音,去河邊找鬼椭盏。 笑死组砚,一個胖子當著我的面吹牛,可吹牛的內容都是我干的掏颊。 我是一名探鬼主播糟红,決...
    沈念sama閱讀 40,193評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼乌叶!你這毒婦竟也來了盆偿?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,074評論 0 276
  • 序言:老撾萬榮一對情侶失蹤准浴,失蹤者是張志新(化名)和其女友劉穎事扭,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體乐横,經...
    沈念sama閱讀 45,505評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡求橄,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,722評論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了葡公。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片罐农。...
    茶點故事閱讀 39,841評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖催什,靈堂內的尸體忽然破棺而出涵亏,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 35,569評論 5 345
  • 正文 年R本政府宣布溯乒,位于F島的核電站夹厌,受9級特大地震影響,放射性物質發(fā)生泄漏裆悄。R本人自食惡果不足惜矛纹,卻給世界環(huán)境...
    茶點故事閱讀 41,168評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望光稼。 院中可真熱鬧或南,春花似錦、人聲如沸艾君。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,783評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽冰垄。三九已至蹬癌,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間虹茶,已是汗流浹背逝薪。 一陣腳步聲響...
    開封第一講書人閱讀 32,918評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留蝴罪,地道東北人董济。 一個月前我還...
    沈念sama閱讀 47,962評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像要门,于是被迫代替她去往敵國和親虏肾。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,781評論 2 354

推薦閱讀更多精彩內容