沙盒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];