常見的NSFileManager文件方法

1改备、常見的NSFileManager文件方法

-(NSData *)contentsAtPath:path  //從一個文件讀取數(shù)據(jù)

-(BOOL)createFileAtPath: path contents:(NSData *)data attributes:attr  //向一個文件寫入數(shù)據(jù)

-(BOOL)removeItemAtPath:path error:err  //刪除一個文件

-(BOOL)moveItemAtPath:from toPath:to error:err  //重命名或者移動一個文件(to不能是已存在的)

-(BOOL)copyItemAtPath:from toPath:to error:err  //復(fù)制文件(to不能是已存在的)

-(BOOL)contentsEqualAtPath:path andPath:path2  //比較兩個文件的內(nèi)容

-(BOOL)fileExistAtPath:path  //測試文件是否存在

-(BOOL)isReadableFileAtPath:path  //測試文件是否存在穗椅,并且是否能執(zhí)行讀操作

-(BOOL)isWriteableFileAtPath:path  //測試文件是否存在,并且是否能執(zhí)行寫操作

-(NSDictionary *)attributesOfItemAtPath:path error:err  //獲取文件的屬性

-(BOOL)setAttributesOfItemAtPath:attr error:err  //更改文件的屬性

2.使用目錄

-(NSString *)currentDirectoryPath  //獲取當(dāng)前目錄

-(BOOL)changeCurrentDirectoryPath:path  //更改當(dāng)前目錄

-(BOOL)copyItemAtPath:from toPath:to error:err  //復(fù)制目錄結(jié)構(gòu)(to不能是已存在的)

-(BOOL)createDirectoryAtPath:path withIntermediateDirectories:(BOOL)flag attribute:attr  //創(chuàng)建一個新目錄

-(BOOL)fileExistAtPath:path isDirectory:(BOOL*)flag  //測試文件是不是目錄(flag中儲存結(jié)果YES/NO)

-(NSArray *)contentsOfDirectoryAtPath:path error:err  //列出目錄內(nèi)容

-(NSDirectoryEnumerator *)enumeratorAtPath:path  //枚舉目錄的內(nèi)容

-(BOOL)removeItemAtPath:path error:err  //刪除空目錄

-(BOOL)moveItemAtPath:from toPath:to error:err   //重命名或移動一個目錄(to不能是已存在的)

3客蹋、常用路徑工具方法

+(NSString *)pathWithComponens:components  //根據(jù)components中的元素構(gòu)造有效路徑

-(NSArray *)pathComponents  //析構(gòu)路徑塞蹭,獲得組成此路徑的各個部分

-(NSString *)lastPathComponent  //提取路徑的最后一個組成部分

-(NSString *)pathExtension  //從路徑的最后一個組成部分中提取其擴(kuò)展名

-(NSString *)stringByAppendingPathComponent:path  //將path添加到現(xiàn)有路徑的末尾

-(NSString *)stringByAppendingPathExtension:ext  //將指定的擴(kuò)展名添加到路徑的最后一個組成部分

-(NSString *)stringByDeletingLastPathComponent  //刪除路徑的最后一個組成部分

-(NSString *)stringByDeletingPathExtension  //從文件的最后一部分刪除擴(kuò)展名

-(NSString *)stringByExpandingTileInPath   //將路徑中代字符擴(kuò)展成用戶主目錄()或指定用戶的主目錄(user)

-(NSString *)stringByresolvingSymlinksInPath  //嘗試解析路徑中的符號鏈接

-(NSString *)stringByStandardizingPath  //通過嘗試解析~、..(父目錄符號)讶坯、.(當(dāng)前目錄符號)和符號鏈接來標(biāo)準(zhǔn)化路徑

4番电、常用的路徑工具函數(shù)

NSString* NSUserName(void)  //返回當(dāng)前用戶的登錄名

NSString* NSFullUserName(void)  //返回當(dāng)前用戶的完整用戶名

NSString* NSHomeDirectory(void)  //返回當(dāng)前用戶主目錄的路徑

NSString* NSHomeDirectoryForUser(NSString* user)  //返回用戶user的主目錄

NSString* NSTemporaryDirectory(void)  //返回可用于創(chuàng)建臨時文件的路徑目錄

5、常用的IOS目錄

Documents(NSDocumentDirectory)  //用于寫入應(yīng)用相關(guān)數(shù)據(jù)文件的目錄辆琅,在ios中寫入這里的文件能夠與iTunes共享并訪問漱办,存儲在這里的文件會自動備份到云端

Library/Caches(NSCachesDirectory)  //用于寫入應(yīng)用支持文件的目錄,保存應(yīng)用程序再次啟動需要的信息婉烟。iTunes不會對這個目錄的內(nèi)容進(jìn)行備份

tmp(use NSTemporaryDirectory())  //這個目錄用于存放臨時文件娩井,只程序終止時需要移除這些文件,當(dāng)應(yīng)用程序不再需要這些臨時文件時似袁,應(yīng)該將其從這個目錄中刪除

Library/Preferences  //這個目錄包含應(yīng)用程序的偏好設(shè)置文件洞辣,使用 NSUserDefault類進(jìn)行偏好設(shè)置文件的創(chuàng)建、讀取和修改

IOS文件操作的兩種方式:NSFileManager操作和流操作

1昙衅、文件的創(chuàng)建

-(IBAction) CreateFile

{

//對于錯誤信息

NSError *error;

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

NSFileManager *fileMgr = [NSFileManager defaultManager];

//指向文件目錄

NSString *documentsDirectory= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

//創(chuàng)建一個目錄

[[NSFileManager defaultManager] createDirectoryAtPath: [NSString stringWithFormat:@"%@/myFolder", NSHomeDirectory()] attributes:nil];

// File we want to create in the documents directory我們想要創(chuàng)建的文件將會出現(xiàn)在文件目錄中

// Result is: /Documents/file1.txt結(jié)果為:/Documents/file1.txt

NSString *filePath= [documentsDirectory

stringByAppendingPathComponent:@"file2.txt"];

//需要寫入的字符串

NSString *str= @"iPhoneDeveloper Tips http://iPhoneDevelopTips,com";

//寫入文件

[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

//顯示文件目錄的內(nèi)容

NSLog(@"Documentsdirectory: contentsOfDirectoryAtPath:documentsDirectory error:&error]);

}

2扬霜、對文件重命名

對一個文件重命名
想要重命名一個文件,我們需要把文件移到一個新的路徑下而涉。下面的代碼創(chuàng)建了我們所期望的目標(biāo)文件的路徑著瓶,然后請求移動文件以及在移動之后顯示文件目錄。
//通過移動該文件對文件重命名
NSString *filePath2= [documentsDirectory
stringByAppendingPathComponent:@"file2.txt"];
//判斷是否移動
if ([fileMgr moveItemAtPath:filePath toPath:filePath2 error:&error] != YES)
NSLog(@"Unable to move file: %@", [error localizedDescription]);
//顯示文件目錄的內(nèi)容
NSLog(@"Documentsdirectory: %@",
[fileMgr contentsOfDirectoryAtPath:documentsDirectoryerror:&error]);

3婴谱、刪除一個文件

為了使這個技巧完整蟹但,讓我們再一起看下如何刪除一個文件:
//在filePath2中判斷是否刪除這個文件
if ([fileMgr removeItemAtPath:filePath2 error:&error] != YES)
NSLog(@"Unable to delete file: %@", [error localizedDescription]);
//顯示文件目錄的內(nèi)容 NSLog(@"Documentsdirectory: %@",
[fileMgr contentsOfDirectoryAtPath:documentsDirectoryerror:&error]);
一旦文件被刪除了躯泰,正如你所預(yù)料的那樣,文件目錄就會被自動清空:

這些示例能教你的华糖,僅僅只是文件處理上的一些皮毛麦向。想要獲得更全面、詳細(xì)的講解客叉,你就需要掌握NSFileManager文件的知識诵竭。

4、刪除目錄下所有文件

//獲取文件路徑 - (NSString *)attchmentFolder{

NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *path = [document stringByAppendingPathComponent:@"Attchments"];

NSFileManager *manager = [NSFileManager defaultManager];

if(![manager contentsOfDirectoryAtPath:path error:nil]){

[manager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];

}

return path;

}

--清除附件 BOOL result = [[NSFileManager defaultManager] removeItemAtPath:[[MOPAppDelegate instance] attchmentFolder] error:nil];

IPhone中獲取文件各項屬性方法

-(NSData *)applicationDataFromFile:(NSString *)fileName
{
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory =[paths objectAtIndex:0];
NSString *appFile =[documentsDirectory stringByAppendingPathComponent:fileName];
NSData *data =[[[NSData alloc]initWithContentsOfFile:appFile]autorelease];
return data;
}

-(void)getFileAttributes
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *path = @"/1ct.rtf";
NSDictionary *fileAttributes = [fileManager fileAttributesAtPath:path traverseLink:YES];
NSLog(@"@@");
if (fileAttributes != nil) {
NSNumber *fileSize;
NSString *fileOwner, *creationDate;
NSDate *fileModDate;
//NSString *NSFileCreationDate

//文件大小
if (fileSize = [fileAttributes objectForKey:NSFileSize]) {
NSLog(@"File size: %qi ", [fileSize unsignedLongLongValue]);
}

//文件創(chuàng)建日期
if (creationDate = [fileAttributes objectForKey:NSFileCreationDate]) {
NSLog(@"File creationDate: %@ ", creationDate);
//textField.text=NSFileCreationDate;
}

//文件所有者
if (fileOwner = [fileAttributes objectForKey:NSFileOwnerAccountName]) {
NSLog(@"Owner: %@ ", fileOwner);
}

//文件修改日期
if (fileModDate = [fileAttributes objectForKey:NSFileModificationDate]) {
NSLog(@"Modification date: %@ ", fileModDate);
}
}
else {
NSLog(@"Path (%@) is invalid.", path);
}
}

///////////////////

文件類型兼搏,文件縮略圖呢卵慰??佛呻?

============================

//獲取當(dāng)前應(yīng)用程序的主目錄 NSString directoryPath =NSHomeDirectory();

//獲取當(dāng)前目錄下的所有文件 NSArray directoryContents = [[NSFileManager defaultManager] directoryContentsAtPath: directoryPath];

//獲取一個文件或文件夾 NSString selectedFile = (NSString)[directoryContents objectAtIndex: indexPath.row];

//拼成一個完整路徑 [directoryPath stringByAppendingPathComponent: selectedFile];

BOOL isDir;

//判斷是否是為目錄

if ([[NSFileManager defaultManager] fileExistsAtPath:selectedPath isDirectory:&isDir] && isDir)

{//目錄
}

else

{//文件
}

//日期格式化 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateStyle:NSDateFormatterMediumStyle];

[dateFormatter setTimeStyle:NSDateFormatterNoStyle];

//數(shù)字格式化

NSNumberFormatter *numberFormatter =[[NSNumberFormatter alloc] init];

[numberFormatter setPositiveFormat: @"#,##0.## bytes"];

//獲取文件屬性

NSDictionary *fileAttributes =[[NSFileManager defaultManager] fileAttributesAtPath: directoryPath traverseLink: YES];

//獲取文件的創(chuàng)建日期

NSDate modificationDate = (NSDate)[fileAttributes objectForKey: NSFileModificationDate];

//獲取文件的字節(jié)大小

NSNumber fileSize = (NSNumber)[fileAttributes objectForKey: NSFileSize];
//格式化文件大小 nsstring A = [numberFormatter stringFromNumber: fileSize];

//格式化文件創(chuàng)建日期

NSstring B =[dateFormatter stringFromDate: modificationDate];

[numberFormatter release];

[dateFormatter release];

//讀取文件內(nèi)容操作- (void) loadFileContentsIntoTextView{ //通過流打開一個文件 NSInputStream *inputStream = [[NSInputStream alloc] initWithFileAtPath: filePath]; [inputStream open];

NSInteger maxLength = 128;

uint8_t readBuffer [maxLength];

//是否已經(jīng)到結(jié)尾標(biāo)識

BOOL endOfStreamReached = NO;

// NOTE: this tight loop will block until stream ends

while (! endOfStreamReached)

{

NSInteger bytesRead = [inputStream read: readBuffer maxLength:maxLength];

if (bytesRead == 0)

{//文件讀取到最后

endOfStreamReached = YES;

}

else if (bytesRead == -1)

{//文件讀取錯誤

endOfStreamReached = YES;

}

else

{

NSString *readBufferString =[[NSString alloc] initWithBytesNoCopy: readBuffer length: bytesRead encoding: NSUTF8StringEncoding freeWhenDone: NO];

//將字符不斷的加載到視圖

[self appendTextToView: readBufferString];

[readBufferString release];

}

}

[inputStream close];

[inputStream release];

}

異步文件的讀取 裳朋,在網(wǎng)絡(luò)方面,由于網(wǎng)絡(luò)的不可靠性可能會造成NSFileManager的文件操作方法的阻塞吓著,而以流的方式進(jìn)行操作則可以實現(xiàn)異步的讀取鲤嫡。

NSStream是可以異步工作的“筝海可以注冊一個在流中有字節(jié)可讀的時候回調(diào)的函數(shù)暖眼,如果沒有可讀的,就不要阻塞住纺裁,回調(diào)出去诫肠。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市欺缘,隨后出現(xiàn)的幾起案子栋豫,更是在濱河造成了極大的恐慌,老刑警劉巖浪南,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件笼才,死亡現(xiàn)場離奇詭異,居然都是意外死亡络凿,警方通過查閱死者的電腦和手機(jī)骡送,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來絮记,“玉大人摔踱,你說我怎么就攤上這事≡狗撸” “怎么了派敷?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長评矩。 經(jīng)常有香客問我纲仍,道長,這世上最難降的妖魔是什么被啼? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任试躏,我火速辦了婚禮猪勇,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘颠蕴。我一直安慰自己泣刹,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布犀被。 她就那樣靜靜地躺著椅您,像睡著了一般。 火紅的嫁衣襯著肌膚如雪寡键。 梳的紋絲不亂的頭發(fā)上掀泳,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天,我揣著相機(jī)與錄音西轩,去河邊找鬼开伏。 笑死,一個胖子當(dāng)著我的面吹牛遭商,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播捅伤,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼劫流,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了丛忆?” 一聲冷哼從身側(cè)響起祠汇,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎熄诡,沒想到半個月后可很,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡凰浮,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年我抠,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片袜茧。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡菜拓,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出笛厦,到底是詐尸還是另有隱情纳鼎,我是刑警寧澤,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站劝贸,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏逗宁。R本人自食惡果不足惜映九,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧僻孝,春花似錦穿铆、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽爱沟。三九已至珍促,卻和暖如春猪叙,著一層夾襖步出監(jiān)牢的瞬間歉嗓,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留惭等,地道東北人珍手。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親琳要。 傳聞我的和親對象是個殘疾皇子寡具,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,713評論 2 354

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