沙盒 文件

沙盒SandBox

向沙盒寫(xiě)文件和讀文件

文件管理NSFileManager

圖片下載

創(chuàng)建文件夾

創(chuàng)建文件

復(fù)制文件

剪切文件/文件夾

刪除文件

查詢文件夾下的文件

文件內(nèi)容管理NSFileHandle

寫(xiě)文件

讀文件

對(duì)大文件進(jìn)行寫(xiě)入

字符串轉(zhuǎn)化為本地URL

沙盒SandBox

類(lèi)似于古代行軍打仗用的沙盤(pán), 一個(gè)沙盤(pán)代表一個(gè)世界.

在iOS中, 每個(gè)ipa應(yīng)用文件, iOS系統(tǒng)都會(huì)給它開(kāi)辟一個(gè)獨(dú)立的存儲(chǔ)空間(磁盤(pán)空間),

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

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

NSString*ipaPath = [[NSBundlemainBundle] bundlePath];

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

returnYES;

//Directory: 文件夾

//Domain: 域, 領(lǐng)域

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

/*

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

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

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

*/

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;

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

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

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

//真機(jī)從iOS9開(kāi)始不再允許使用軟件訪問(wèn)沙盒

NSString*rootPath =NSHomeDirectory();

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

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

//下方方法會(huì)在拼接字符串時(shí),自動(dòng)在中間添加 /

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);

向沙盒寫(xiě)文件和讀文件

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

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

//字典寫(xiě)文件--> ~/Documents/字典

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

@"日期":@"20160127",

@"學(xué)生":@[@"張三",@"李四"],

@"學(xué)號(hào)": @221212312};

//拼出文件地址

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

//寫(xiě)入文件

[dic writeToFile:dicPath atomically:YES];

//讀出文件內(nèi)容

NSDictionary*readDic = [NSDictionarydictionaryWithContentsOfFile:dicPath];

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

returnYES;

//數(shù)組寫(xiě)文件---> ~/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;

//把字符串 寫(xiě)到 ~/Documents/文本

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

/*

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

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

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

參數(shù)4: 二級(jí)指針 **類(lèi)型, 當(dāng)有錯(cuò)誤發(fā)生時(shí),就會(huì)對(duì)這個(gè)指針進(jìn)行賦值

*/

NSError*error =nil;

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

if(error) {

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

}

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

//讀取文件--要使用與文件內(nèi)容匹配的類(lèi)型來(lái)讀取文件內(nèi)容

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

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

文件管理NSFileManager

圖片下載

使用多線程下載圖片, 下載完畢以后存儲(chǔ)在硬盤(pán)上. 當(dāng)再次下載時(shí), 從硬盤(pán)讀取, 不再請(qǐng)求.

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

//文件管理類(lèi): 可以對(duì)文件/文件夾進(jìn)行 增刪改移動(dòng)等操作

NSFileManager*manager = [NSFileManagerdefaultManager];

//判斷某個(gè)文件是否存在 exist

BOOLfileExist = [manager fileExistsAtPath:path];

if(fileExist) {

_imageView.image= [UIImageimageWithContentsOfFile:path];

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

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

}

[[NSOperationQueuenew] addOperationWithBlock:^{

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

//寫(xiě)入到~/Documents/'圖片名'

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

//data ->寫(xiě)入->文件中

[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:自動(dòng)創(chuàng)建中間文件夾. ~/Docments/2/3

如果2文件夾不存在?

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

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

*/

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

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

創(chuàng)建文件

//通過(guò)文件管理器創(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];

復(fù)制文件

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

文件內(nèi)容管理NSFileHandle

寫(xiě)文件

//創(chuàng)建文件

- (void)createFile{

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

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

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

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

//2.通過(guò)fileHandle向文件中寫(xiě)入內(nèi)容

//fileHandle 分為寫(xiě)操作和讀操作

NSFileHandle*fileHandle = [NSFileHandlefileHandleForWritingAtPath:path];

//準(zhǔn)備寫(xiě)入的內(nèi)容

NSString*content =@"使用FileHandle寫(xiě)入內(nèi)容";

//開(kāi)始寫(xiě)

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

//關(guān)閉寫(xiě)入操作

[fileHandle closeFile];

}

讀文件

//寫(xiě)小的文件內(nèi)容--復(fù)制

- (void)copySmallFile{

//操作:把File.txt中的內(nèi)容讀出來(lái), 然后寫(xiě)入到文件Target.txt中

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

NSFileHandle*readHandle = [NSFileHandlefileHandleForReadingAtPath:path];

//使用讀操作 讀取全部?jī)?nèi)容

NSData*data = [readHandle readDataToEndOfFile];

[readHandle closeFile];

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

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

NSLog(@"%@", kDocPath);

}

對(duì)大文件進(jìn)行寫(xiě)入

//寫(xiě)大的文件內(nèi)容- 復(fù)制(準(zhǔn)備一個(gè)pdf)

- (void)copyBigFile{

//內(nèi)存只有2G, 當(dāng)要寫(xiě)一個(gè)超過(guò)2G的文件時(shí),就不能夠直接把文件都讀取到內(nèi)存中,再寫(xiě)入.需要分段讀寫(xiě)

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

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

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

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

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

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

//讀源文件

NSFileHandle*readHandle = [NSFileHandlefileHandleForReadingAtPath:pdfPath];

//寫(xiě)到目標(biāo)文件

NSFileHandle*writeHandle = [NSFileHandlefileHandleForWritingAtPath:targetPath];

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

NSIntegersizePerTime =5000;

//當(dāng)前已經(jīng)讀取的大小

NSIntegerreadSize =0;

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

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

//總大小

NSNumber*fileTotalSize = attr[NSFileSize];

NSIntegerfileTotalLenght = fileTotalSize.integerValue;

//標(biāo)識(shí): 控制當(dāng)前循環(huán)是否要繼續(xù)

BOOLnotEnd =YES;

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

intcount =0;

while(notEnd) {

//計(jì)算剩余數(shù)據(jù)長(zhǎng)度

NSIntegerleftLength = fileTotalLenght - readSize;

NSData*data =nil;

if(leftLength >= sizePerTime) {

//剩余內(nèi)容足夠再讀取至少一次

data = [readHandle readDataOfLength:sizePerTime];

//每次讀取,都把已經(jīng)讀取的長(zhǎng)度加上5000,并且把讀操作的指針挪到新的開(kāi)始位置

readSize += sizePerTime;

[readHandle seekToFileOffset:readSize];

}else{

//不足一次

notEnd =NO;

//把剩下的讀完

data = [readHandle readDataOfLength:leftLength];

}

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

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

}

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

}

字符串轉(zhuǎn)化為本地URL

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

//文件路徑 URL類(lèi)型

NSURL*fileURL = [NSURLfileURLWithPath:dir0];

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容