IOS文件管理

iOS開發(fā)-文件管理(一)

一、iOS中的沙盒機(jī)制

iOS應(yīng)用程序只能對(duì)自己創(chuàng)建的文件系統(tǒng)讀取文件,這個(gè)獨(dú)立、封閉、安全的空間,叫做沙盒。它一般存放著程序包文件(可執(zhí)行文件)、圖片、音頻、視頻、plist文件、sqlite數(shù)據(jù)庫(kù)以及其他文件。

每個(gè)應(yīng)用程序都有自己的獨(dú)立的存儲(chǔ)空間(沙盒)

一般來說應(yīng)用程序之間是不可以互相訪問

模擬器沙盒的位置

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

當(dāng)我們創(chuàng)建應(yīng)用程序時(shí),在每個(gè)沙盒中含有三個(gè)文件,分別是Document、Library和temp。

Document:一般需要持久的數(shù)據(jù)都放在此目錄中,可以在當(dāng)中添加子文件夾,iTunes備份和恢復(fù)的時(shí)候,會(huì)包括此目錄。

Library:設(shè)置程序的默認(rèn)設(shè)置和其他狀態(tài)信息

temp:創(chuàng)建臨時(shí)文件的目錄,當(dāng)iOS設(shè)備重啟時(shí),文件會(huì)被自動(dòng)清除

獲取沙盒目錄

獲取程序的根目錄(home)目錄

NSString *homePath = NSHomeDirectory()

獲取Document目錄

NSArray

*paths = NSSearchPathDorDirectoriesInDomains(NSDocumentDicrectory,,

NSUserDomainMark,

YES);

NSString *docPath = [paths lastObject];

獲取Library目錄

NSArray

*paths = NSSearchPathForDirectoriseInDomains(NSLibraryDirectory,

NSUserDomainMask,

YES);

NSString *docPath = [paths lastObject];

獲取Library中的Cache

NSArray

*paths = NSSearchPathForDirectoriseInDomains(NSCachesDirectory,

NSUserDomainMask,

YES);

NSString *docPath = [paths lastObject];

獲取temp路徑

NSString *temp = NSTemporaryDirectory( );

二、NSString類路徑的處理方法

文件路徑的處理

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

常用方法如下

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

- (NSArray *)pathComponents;

提取路徑的最后一個(gè)組成部分,結(jié)果:testfile.txt

- (NSString *)lastPathComponent;

刪除路徑的最后一個(gè)組成部分,結(jié)果:/Users/apple

- (NSString *)stringByDeletingLastPathCpmponent;

將path添加到先郵路徑的末尾,結(jié)果:/Users/apple/testfile.txt/app.txt

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

去路徑最后部分的擴(kuò)展名,結(jié)果:text

- (NSString *)pathExtension;

刪除路徑最后部分的擴(kuò)展名,結(jié)果:/Users/apple/testfile

- (NSString *)stringByDeletingPathExtension;

路徑最后部分追加擴(kuò)展名,結(jié)果:/User/apple/testfile.txt.jpg

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

三、NSData

NSData是用來包裝數(shù)據(jù)的

NSData存儲(chǔ)的是二進(jìn)制數(shù)據(jù),屏蔽了數(shù)據(jù)之間的差異,文本、音頻、圖像等數(shù)據(jù)都可用NSData來存儲(chǔ)

NSData的用法

1.NSString與NSData互相轉(zhuǎn)換

NSData->

NSString

NSString *aString = [[NSString alloc]

initWithData:adataencoding:NSUTF8StringEncoding];

NSString->NSData? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? NSString *aString = @"1234abcd";

NSData *aData = [aString dataUsingEncoding: NSUTF8StringEncoding];

將data類型的數(shù)據(jù),轉(zhuǎn)成UTF8的數(shù)據(jù)

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

{

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

return [buf autorelease];

}

將string轉(zhuǎn)換為指定編碼

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

//例:從本地文件沙盒中取圖片并轉(zhuǎn)換為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寫進(jìn)Documents目錄

從Documents目錄讀取數(shù)據(jù)

在進(jìn)行網(wǎng)絡(luò)數(shù)據(jù)通信的時(shí)候,經(jīng)常會(huì)遇到NSData類型的數(shù)據(jù)。在該數(shù)據(jù)是dictionary結(jié)構(gòu)的情況下,系統(tǒng)沒有提供現(xiàn)成的轉(zhuǎn)換成NSDictionary的方法,為此可以通過Category對(duì)NSDictionary進(jìn)行擴(kuò)展,以支持從NSData到NSDictionary的轉(zhuǎn)換。聲明和實(shí)現(xiàn)如下:

+ (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

創(chuàng)建一個(gè)文件并寫入數(shù)據(jù)- (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSDictionary *)attr;

從一個(gè)文件中讀取數(shù)據(jù)- (NSData *)contentsAtPath:(NSString *)path;

scrPath路徑上的文件移動(dòng)到dstPath路徑上,注意這里的路徑是文件路徑而不是目錄- (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **) error;

scrPath路徑上的文件復(fù)制到dstPath路徑上- (BOOL)copyItemAtPath:(NSString *)scrPath toPath:(NSString *)dstPath error:(NSError **) error;

比較兩個(gè)文件的內(nèi)容是否一樣- (BOOL)contentsEqualAtPath:(NSString *)path1 andPath:(NSString *)path2;

文件時(shí)候存在- (BOOL)fileExistsAtPath:(NSString *)path;

移除文件- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **) error;

創(chuàng)建文件管理

NSFileManager

*fileManager = [NSFileManager defaultManager];

NSString *path = [NSHomeDirectory( )

stringByAppendingPathComponent:@"holyBible.txt"];

NSString *text = @"abcdefg";

將字符串轉(zhuǎn)成NSData類型NSData *data = [text dataUsingEncoding: NSUTF8StringEncoding];

寫入文件BOOL success = [fileManager createFileAtPath:path contents:data attributes:nil];

創(chuàng)建文件夾

NSString

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

NSString

*contect = @"abcdefg";

BOOL success = [fm createFileAtPath:filePath contents:[content

dataUsingEncoding: NSUTF8StringEncoding] attributes:nil];

NSFileManager-讀取內(nèi)容NSData *fileData = [fileManager contentsAtPath:filePath];? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? NSString *content = [[NSString alloc] initWithData:fileData dataUsingEncoding: NSUTF8StringEncoding];

NSData-讀取內(nèi)容NSString *filePath = [path stringByAppendingPathComponent:@"holyBible.txt"];? ? NSData *data = [NSData dataWithContentOfFile:filePath];

NSString-讀取內(nèi)容NSString *filePath = [path stringByAppendingPathComponent:@"holyBible.txt"];? ? NSString *content = [[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

移動(dòng)、復(fù)制文件

移動(dòng)文件(重命名)NSString *toPath = [NSHomeDirectory( ) stringByAppendingPathComponent:@"hellogod/New Testament.txt"];? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? [fm createDirectoryAtPath:[toPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? NSError *error;? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? BOOL isSuccess = [fm moveItemAtPath:filePath toPath:toPath error:&error];

復(fù)制文件(重命名)NSString *copyPath = [NSHomeDirectory( ) stringByAppendingPathComponent:@"備份/Old Testament.txt"];[fm createDirectoryAtPath:[toPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? BOOL success = [fm copyItemAtPath:toPath toPath:toPath error:nil];

刪除文件、獲取文件大小

判斷文件是否存在和刪除文件if([fm fileExistsAtPath])? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? {? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if ([fm removeItemAtPath:copyPath])? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? {? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 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開發(fā)-文件管理(二)

五、Plist文件

String方式添加

NSString *path = [NSHomeDirectory( )? stringByAppendingPathComponent:@"Array.plist"];

NSString *content = @"abcd";

[contect writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];

Array方式添加

NSString *path = [NSHomeDirectory( )? stringByAppendingPathComponent:@"Array.plist"];

[NSArray *array = [[NSArray alloc] initWithObjects:@"123", @"798",@"000",nil];? ? ? [array writeToFile:path atomically:YES];

Dictionary方式添加

NSString *path = [NSHomeDirectory( )? stringByAppendingPathComponent:@"Dic.plist"];

NSDictionary *dic = [NSDictionary alloc] initWithObjects:@"first",@"second",@"third"forKeys:@"123",@"456",@"798"];? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? [dic writeToFile:path atomically:YES];

數(shù)組、字典只能將BOOL、NSNumber、NSString、NSData、NSDate、NSArray、NSDictionary寫入屬性列表plist文件

六、讀取文件類和常用方法

NSFileHandle類主要對(duì)文件內(nèi)容進(jìn)行讀取和寫入操作

NSFileManager類主要對(duì)文件的操作(刪除、修改、移動(dòng)、復(fù)制等等)

常用處理方法

+ (id)fileHandleForReadingAtPath:(NSString *)path? 打開一個(gè)文件準(zhǔn)備讀取

+ (id)fileHandleForWritingAtPath:(NSString *)path? 打開一個(gè)文件準(zhǔn)備寫入

+ (id)fileHandleForUpdatingAtPath:(NSString *)path? 打開一個(gè)文件準(zhǔn)備更新

-? (NSData *)availableData; 從設(shè)備或通道返回可用的數(shù)據(jù)

-? (NSData *)readDataToEndOfFile; 從當(dāng)前的節(jié)點(diǎn)讀取到文件的末尾

-? (NSData *)readDataOfLength:(NSUInteger)length; 從當(dāng)前節(jié)點(diǎn)開始讀取指定的長(zhǎng)度數(shù)據(jù)

-? (void)writeData:(NSData *)data; 寫入數(shù)據(jù)

-? (unsigned long long)offsetInFile;? 獲取當(dāng)前文件的偏移量

-? (void)seekToFileOffset:(unsigned long long)offset; 跳到指定文件的偏移量

-? (unsigned long long)seekToEndOfFile; 跳到文件末尾

-? (void)truncateFileAtOffset:(unsigned long long)offset; 將文件的長(zhǎng)度設(shè)為offset字節(jié)

-? (void)closeFile;? 關(guān)閉文件

向文件追加數(shù)據(jù)

NSString *homePath? = NSHomeDirectory( );

NSString *sourcePath = [homePath stringByAppendingPathConmpone:@"testfile.text"];

NSFileHandle

*fielHandle = [NSFileHandle

fileHandleForUpdatingAtPath:sourcePath];

[fileHandle seekToEndOfFile];? 將節(jié)點(diǎn)跳到文件的末尾

NSString *str = @"追加的數(shù)據(jù)"

NSData* stringData? = [str dataUsingEncoding:NSUTF8StringEncoding];

[fileHandle writeData:stringData]; 追加寫入數(shù)據(jù)

[fileHandle closeFile];

定位數(shù)據(jù)

NSFileManager *fm = [NSFileManager defaultManager];

NSString *content = @"abcdef";

[fm

createFileAtPath:path contents:[content

dataUsingEncoding:NSUTF8StringEncoding]

attributes:nil];

NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:path];

NSUInteger length = [fileHandle availabelData] length]; 獲取數(shù)據(jù)長(zhǎng)度

[fileHandle seekToFileOffset;length/2]; 偏移量文件的一半

NSData *data = [fileHandle readDataToEndOfFile];

[fileHandle closeFile];

復(fù)制文件

NSFileHandle *infile, *outfile; 輸入文件、輸出文件

NSData *buffer; 讀取的緩沖數(shù)據(jù)

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *homePath = NSHomeDirectory( );

NSString

*sourcePath = [homePath

stringByAppendingPathComponent:@"testfile.txt"];? 源文件路

NSString *outPath = [homePath stringByAppendingPathComponent:@"outfile.txt"]; 輸出文件路徑

BOOL sucess? = [fileManager createFileAtPath:outPath contents:nil attributes:nil];

if (!success)

{

return N0;

}

infile = [NSFileHandle fileHandleForReadingAtPath:sourcePath]; 創(chuàng)建讀取源路徑文件

if (infile == nil)

{

return NO;

}

outfile

= [NSFileHandle

fileHandleForReadingAtPath:outPath]; 創(chuàng)建并打開要輸出的文

if (outfile == nil)

{

return NO;

}

[outfile truncateFileAtOffset:0]; 將輸出文件的長(zhǎng)度設(shè)為0

buffer = [infile readDataToEndOfFile];? 讀取數(shù)據(jù)

[outfile writeData:buffer];? 寫入輸入

[infile closeFile];? ? ? ? 關(guān)閉寫入、輸入文件

[outfile closeFile];

注:筆記轉(zhuǎn)載自MacShare

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、iOS中的沙盒機(jī)制 iOS應(yīng)用程序只能對(duì)自己創(chuàng)建的文件系統(tǒng)讀取文件,這個(gè)獨(dú)立、封閉、安全的空間,叫做沙盒。它一...
    tzhtodd閱讀 1,338評(píng)論 0 2
  • iOS開發(fā)-文件管理(一) 一、iOS中的沙盒機(jī)制 iOS應(yīng)用程序只能對(duì)自己創(chuàng)建的文件系統(tǒng)讀取文件,這個(gè)獨(dú)立、封閉...
    MacShare閱讀 1,857評(píng)論 0 6
  • 一、iOS中的沙盒機(jī)制 iOS應(yīng)用程序只能對(duì)自己創(chuàng)建的文件系統(tǒng)讀取文件,這個(gè)獨(dú)立、封閉、安全的空間,叫做沙盒。它一...
    絢雨藍(lán)了個(gè)楓閱讀 4,309評(píng)論 0 2
  • 一、iOS中的沙盒機(jī)制 ?iOS應(yīng)用程序只能對(duì)自己創(chuàng)建的文件系統(tǒng)讀取文件,這個(gè)獨(dú)立、封閉、安全的空間,叫做沙盒。它...
    舒城8中閱讀 2,515評(píng)論 0 6
  • iOS文件管理系統(tǒng)NSFileManager使用詳解 1,找到自己的程序的目錄: NSHomeDirectory(...
    lhg_serven閱讀 11,446評(píng)論 0 4

友情鏈接更多精彩內(nèi)容