沙盒 文件

沙盒SandBox

向沙盒寫文件和讀文件

文件管理NSFileManager

圖片下載

創(chuàng)建文件夾

創(chuàng)建文件

復制文件

剪切文件/文件夾

刪除文件

查詢文件夾下的文件

文件內容管理NSFileHandle

寫文件

讀文件

對大文件進行寫入

字符串轉化為本地URL

沙盒SandBox

類似于古代行軍打仗用的沙盤, 一個沙盤代表一個世界.

在iOS中, 每個ipa應用文件, iOS系統(tǒng)都會給它開辟一個獨立的存儲空間(磁盤空間),

這些ipa的磁盤空間在非越獄情況下, 是無法互相交流的.這是為了保證安全

//查找ipa文件--程序文件存儲位置, Bundle:束

NSString*ipaPath = [[NSBundlemainBundle] bundlePath];

NSLog(@"ipaPath: %@", ipaPath);

returnYES;

//Directory: 文件夾

//Domain: 域, 領域

//expand 拓展tilde波浪字符 ~/Docuemnts

/*

參數(shù)1: 枚舉類型,代表要查找的文件夾類型

參數(shù)2: 代表搜索的范圍

參數(shù)3: YES代表 展開波浪, 即 全路徑

*/

NSString*docPath0 =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObject;

NSLog(@"docPath0: %@", docPath0);

//LibraryNSLibraryDirectory

NSString*libPath0 =NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES).firstObject;

NSLog(@"libPath0: %@", libPath0);

//Library/CachesNSCachesDirectory

NSString*cachePath =NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES).firstObject;

NSLog(@"cachePath: %@", cachePath);

//獲取tmp路徑

NSString*tmpPath0 =NSTemporaryDirectory();

NSLog(@"tmpPath0: %@", tmpPath0);

returnYES;

//沙盒中默認有幾個文件夾, 用于存放數(shù)據(jù)

//獲取沙盒路徑--每次獲取都不同,文件夾名稱被加密

//模擬器可以通過 Finder的前往文件夾功能查看沙盒.

//真機從iOS9開始不再允許使用軟件訪問沙盒

NSString*rootPath =NSHomeDirectory();

NSLog(@"rootPath: %@", rootPath);

//獲取Document文件夾-> root/Documents

//下方方法會在拼接字符串時,自動在中間添加 /

NSString*docPath = [rootPath stringByAppendingPathComponent:@"Documents"];

NSLog(@"docPath: %@", docPath);

//Library

NSString*libPath = [rootPath stringByAppendingPathComponent:@"Library"];

NSLog(@"libPath: %@", libPath);

//tmp

NSString*tmpPath = [rootPath stringByAppendingPathComponent:@"tmp"];

NSLog(@"tmpPath: %@", tmpPath);

向沙盒寫文件和讀文件

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

NSLog(@"docPath: %@", docPath);

//字典寫文件--> ~/Documents/字典

NSDictionary*dic = @{@"name":@"1511A",

@"日期":@"20160127",

@"學生":@[@"張三",@"李四"],

@"學號": @221212312};

//拼出文件地址

NSString*dicPath = [docPath stringByAppendingPathComponent:@"字典"];

//寫入文件

[dic writeToFile:dicPath atomically:YES];

//讀出文件內容

NSDictionary*readDic = [NSDictionarydictionaryWithContentsOfFile:dicPath];

NSLog(@"readDic %@", readDic);

returnYES;

//數(shù)組寫文件---> ~/Documents/數(shù)組

NSArray*arr = @[@"騰訊",

@1,

@YES,

@{@"name":@"1511A"}];

NSString*arrPath = [docPath stringByAppendingPathComponent:@"數(shù)組"];

[arr writeToFile:arrPath atomically:YES];

NSArray*readArr = [NSArrayarrayWithContentsOfFile:arrPath];

NSLog(@"readArr: %@", readArr);

returnYES;

//把字符串 寫到 ~/Documents/文本

NSString*txtPath = [docPath stringByAppendingPathComponent:@"文本"];

/*

參數(shù)1: 文件的路徑

參數(shù)2: YES代表生成輔助文件, 寫入的時候先寫到輔助文件里, 寫完以后再復制到真實目錄下. 這樣可以防止中途發(fā)生問題

參數(shù)3: 編碼, 通常都使用UTF8編碼

參數(shù)4: 二級指針 **類型, 當有錯誤發(fā)生時,就會對這個指針進行賦值

*/

NSError*error =nil;

[@"kkwerqesadfewqrsdf"writeToFile:txtPath atomically:YESencoding:NSUTF8StringEncodingerror:&error];

if(error) {

NSLog(@"error %@", error);

}

NSLog(@"docPath: %@", docPath);

//讀取文件--要使用與文件內容匹配的類型來讀取文件內容

NSString*content = [NSStringstringWithContentsOfFile:txtPath encoding:NSUTF8StringEncodingerror:&error];

NSLog(@"content: %@", content);

文件管理NSFileManager

圖片下載

使用多線程下載圖片, 下載完畢以后存儲在硬盤上. 當再次下載時, 從硬盤讀取, 不再請求.

NSString*address =@"http://h.hiphotos.baidu.com/image/pic/item/9d82d158ccbf6c812f9fe0e1be3eb13533fa400b.jpg";

//1.下載圖片

//2.圖片存本地

//3.讀取本地圖片顯示在界面上

NSString*imageName = address.lastPathComponent;

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

//拼接地址

NSString*path = [docPath stringByAppendingPathComponent:imageName];

//文件管理類: 可以對文件/文件夾進行 增刪改移動等操作

NSFileManager*manager = [NSFileManagerdefaultManager];

//判斷某個文件是否存在 exist

BOOLfileExist = [manager fileExistsAtPath:path];

if(fileExist) {

_imageView.image= [UIImageimageWithContentsOfFile:path];

NSLog(@"path %@", path);

return;//下方代碼不再執(zhí)行

}

[[NSOperationQueuenew] addOperationWithBlock:^{

NSData*data = [NSDatadataWithContentsOfURL:[NSURLURLWithString:address]];

//寫入到~/Documents/'圖片名'

//取得地址中最后/后面的部分,作為圖片名

//data ->寫入->文件中

[data writeToFile:path atomically:YES];

NSLog(@"path %@", path);

UIImage*image= [UIImageimageWithContentsOfFile:path];

//回主線程 把圖片給用戶看

[[NSOperationQueuemainQueue] addOperationWithBlock:^{

_imageView.image= image;

}];

}];

創(chuàng)建文件夾

NSString*dir0 = [self.docPathstringByAppendingPathComponent:@"dir0"];

NSString*dir1 = [self.docPathstringByAppendingPathComponent:@"dir1"];

//文件管理器

NSFileManager*manager = [NSFileManagerdefaultManager];

/*

參數(shù)2:自動創(chuàng)建中間文件夾. ~/Docments/2/3

如果2文件夾不存在?

那么參數(shù)是YES,表示自動創(chuàng)建2

參數(shù)是NO, 表示不創(chuàng)建2, 3就會創(chuàng)建失敗

*/

[manager createDirectoryAtPath:dir0 withIntermediateDirectories:YESattributes:nilerror:nil];

[manager createDirectoryAtPath:dir1 withIntermediateDirectories:YESattributes:nilerror:nil];

創(chuàng)建文件

//通過文件管理器創(chuàng)建文件

NSString*dir0Txt = [dir0 stringByAppendingPathComponent:@"dir0.txt"];

NSString*dir1Txt = [dir1 stringByAppendingPathComponent:@"dir1.txt"];

[manager createFileAtPath:dir0Txt contents:nilattributes:nil];

[manager createFileAtPath:dir1Txt contents:nilattributes:nil];

復制文件

NSString*dir1Txt = [self.docPathstringByAppendingPathComponent:@"dir1/dir1.txt"];

// dir0/dir1New.txt

NSString*dir1_New = [self.docPathstringByAppendingPathComponent:@"dir0/dir1New.txt"];

[[NSFileManagerdefaultManager] copyItemAtPath:dir1Txt toPath:dir1_New error:nil];

剪切文件/文件夾

NSString*dir0Txt = [self.docPathstringByAppendingPathComponent:@"dir0/dir0.txt"];

NSString*dir0_new = [self.docPathstringByAppendingPathComponent:@"dir1/dir1_new.txt"];

[[NSFileManagerdefaultManager] moveItemAtPath:dir0Txt toPath:dir0_new error:nil];

刪除文件

[[NSFileManager defaultManager]removeItemAtPath:nil error:nil];

查詢文件夾下的文件

NSString*dir1 = [self.docPathstringByAppendingPathComponent:@"dir1"];

NSFileManager*manager = [NSFileManagerdefaultManager];

NSArray*arr = [manager subpathsAtPath:dir1];

文件內容管理NSFileHandle

寫文件

//創(chuàng)建文件

- (void)createFile{

//1.創(chuàng)建一個空白的文件 ~/Documents/File.txt

NSString*path = [kDocPath stringByAppendingPathComponent:@"File.txt"];

[[NSFileManagerdefaultManager] createFileAtPath:path contents:nilattributes:nil];

NSLog(@"path %@", path);

//2.通過fileHandle向文件中寫入內容

//fileHandle 分為寫操作和讀操作

NSFileHandle*fileHandle = [NSFileHandlefileHandleForWritingAtPath:path];

//準備寫入的內容

NSString*content =@"使用FileHandle寫入內容";

//開始寫

[fileHandle writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];

//關閉寫入操作

[fileHandle closeFile];

}

讀文件

//寫小的文件內容--復制

- (void)copySmallFile{

//操作:把File.txt中的內容讀出來, 然后寫入到文件Target.txt中

NSString*path = [kDocPath stringByAppendingPathComponent:@"File.txt"];

NSFileHandle*readHandle = [NSFileHandlefileHandleForReadingAtPath:path];

//使用讀操作 讀取全部內容

NSData*data = [readHandle readDataToEndOfFile];

[readHandle closeFile];

NSString*targetPath = [kDocPath stringByAppendingPathComponent:@"Target.txt"];

[[NSFileManagerdefaultManager] createFileAtPath:targetPath contents:data attributes:nil];

NSLog(@"%@", kDocPath);

}

對大文件進行寫入

//寫大的文件內容- 復制(準備一個pdf)

- (void)copyBigFile{

//內存只有2G, 當要寫一個超過2G的文件時,就不能夠直接把文件都讀取到內存中,再寫入.需要分段讀寫

//拿到ipa目錄下的pdf文件路徑, Day19.pdf

NSString*pdfPath = [[NSBundlemainBundle] pathForResource:@"Day19"ofType:@"pdf"];

//創(chuàng)建要寫入的文件 ~/Documents/target.pdf

NSString*targetPath = [kDocPath stringByAppendingPathComponent:@"Day19.pdf"];

[[NSFileManagerdefaultManager] createFileAtPath:targetPath contents:nilattributes:nil];

NSLog(@"taregetPath %@", targetPath);

//讀源文件

NSFileHandle*readHandle = [NSFileHandlefileHandleForReadingAtPath:pdfPath];

//寫到目標文件

NSFileHandle*writeHandle = [NSFileHandlefileHandleForWritingAtPath:targetPath];

//每次讀取的大小 單位是字節(jié)

NSIntegersizePerTime =5000;

//當前已經讀取的大小

NSIntegerreadSize =0;

//獲取源文件的屬性, 可以自己NSLog看字典內容

NSDictionary*attr = [[NSFileManagerdefaultManager] attributesOfItemAtPath:pdfPath error:nil];

//總大小

NSNumber*fileTotalSize = attr[NSFileSize];

NSIntegerfileTotalLenght = fileTotalSize.integerValue;

//標識: 控制當前循環(huán)是否要繼續(xù)

BOOLnotEnd =YES;

//記錄共循環(huán)了多少次

intcount =0;

while(notEnd) {

//計算剩余數(shù)據(jù)長度

NSIntegerleftLength = fileTotalLenght - readSize;

NSData*data =nil;

if(leftLength >= sizePerTime) {

//剩余內容足夠再讀取至少一次

data = [readHandle readDataOfLength:sizePerTime];

//每次讀取,都把已經讀取的長度加上5000,并且把讀操作的指針挪到新的開始位置

readSize += sizePerTime;

[readHandle seekToFileOffset:readSize];

}else{

//不足一次

notEnd =NO;

//把剩下的讀完

data = [readHandle readDataOfLength:leftLength];

}

[writeHandle writeData:data];//寫入數(shù)據(jù)

count ++;//讀取次數(shù)加1

}

NSLog(@"共讀取%d次, 路徑%@", count, targetPath);

}

字符串轉化為本地URL

NSString*dir0 = [self.docPathstringByAppendingPathComponent:@"dir0"];

//文件路徑 URL類型

NSURL*fileURL = [NSURLfileURLWithPath:dir0];

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末涌攻,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子壳影,更是在濱河造成了極大的恐慌晌该,老刑警劉巖肥荔,帶你破解...
    沈念sama閱讀 221,820評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異朝群,居然都是意外死亡燕耿,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評論 3 399
  • 文/潘曉璐 我一進店門姜胖,熙熙樓的掌柜王于貴愁眉苦臉地迎上來誉帅,“玉大人,你說我怎么就攤上這事⊙料牵” “怎么了档插?”我有些...
    開封第一講書人閱讀 168,324評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長亚再。 經常有香客問我郭膛,道長,這世上最難降的妖魔是什么氛悬? 我笑而不...
    開封第一講書人閱讀 59,714評論 1 297
  • 正文 為了忘掉前任则剃,我火速辦了婚禮,結果婚禮上圆雁,老公的妹妹穿的比我還像新娘忍级。我一直安慰自己,他們只是感情好伪朽,可當我...
    茶點故事閱讀 68,724評論 6 397
  • 文/花漫 我一把揭開白布轴咱。 她就那樣靜靜地躺著,像睡著了一般烈涮。 火紅的嫁衣襯著肌膚如雪朴肺。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,328評論 1 310
  • 那天坚洽,我揣著相機與錄音戈稿,去河邊找鬼。 笑死讶舰,一個胖子當著我的面吹牛鞍盗,可吹牛的內容都是我干的。 我是一名探鬼主播跳昼,決...
    沈念sama閱讀 40,897評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼般甲,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了鹅颊?” 一聲冷哼從身側響起敷存,我...
    開封第一講書人閱讀 39,804評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎堪伍,沒想到半個月后锚烦,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 46,345評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡帝雇,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,431評論 3 340
  • 正文 我和宋清朗相戀三年涮俄,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片摊求。...
    茶點故事閱讀 40,561評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡禽拔,死狀恐怖刘离,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情睹栖,我是刑警寧澤硫惕,帶...
    沈念sama閱讀 36,238評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站野来,受9級特大地震影響恼除,放射性物質發(fā)生泄漏。R本人自食惡果不足惜曼氛,卻給世界環(huán)境...
    茶點故事閱讀 41,928評論 3 334
  • 文/蒙蒙 一豁辉、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧舀患,春花似錦徽级、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,417評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至低匙,卻和暖如春旷痕,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背顽冶。 一陣腳步聲響...
    開封第一講書人閱讀 33,528評論 1 272
  • 我被黑心中介騙來泰國打工欺抗, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人强重。 一個月前我還...
    沈念sama閱讀 48,983評論 3 376
  • 正文 我出身青樓绞呈,卻偏偏與公主長得像,于是被迫代替她去往敵國和親间景。 傳聞我的和親對象是個殘疾皇子报强,可洞房花燭夜當晚...
    茶點故事閱讀 45,573評論 2 359

推薦閱讀更多精彩內容