常見的NSFileManager文件方法

1、常見的NSFileManager文件方法

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

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

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

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

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

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

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

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

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

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

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

2.使用目錄

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

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

-(BOOL)copyItemAtPath:from toPath:to error:err  //復制目錄結構(to不能是已存在的)

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

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

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

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

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

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

3炕檩、常用路徑工具方法

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

-(NSArray *)pathComponents  //析構路徑笛质,獲得組成此路徑的各個部分

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

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

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

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

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

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

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

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

-(NSString *)stringByStandardizingPath  //通過嘗試解析~妇押、..(父目錄符號)敲霍、.(當前目錄符號)和符號鏈接來標準化路徑

4、常用的路徑工具函數

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

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

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

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

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

5潭袱、常用的IOS目錄

Documents(NSDocumentDirectory)  //用于寫入應用相關數據文件的目錄锋恬,在ios中寫入這里的文件能夠與iTunes共享并訪問与学,存儲在這里的文件會自動備份到云端

Library/Caches(NSCachesDirectory)  //用于寫入應用支持文件的目錄,保存應用程序再次啟動需要的信息晕窑。iTunes不會對這個目錄的內容進行備份

tmp(use NSTemporaryDirectory())  //這個目錄用于存放臨時文件杨赤,只程序終止時需要移除這些文件截汪,當應用程序不再需要這些臨時文件時衙解,應該將其從這個目錄中刪除

Library/Preferences  //這個目錄包含應用程序的偏好設置文件,使用 NSUserDefault類進行偏好設置文件的創(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結果為:/Documents/file1.txt

NSString *filePath= [documentsDirectory

stringByAppendingPathComponent:@"file2.txt"];

**//需要寫入的字符串**

NSString *str= @"iPhoneDeveloper Tips [http://iPhoneDevelopTips,com](https://links.jianshu.com/go?to=http%3A%2F%2FiPhoneDevelopTips%2Ccom)";

**//寫入文件**

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

**//顯示文件目錄的內容**

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

}

2避消、對文件重命名

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

3、刪除一個文件

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

這些示例能教你的,僅僅只是文件處理上的一些皮毛祖凫。想要獲得更全面惠况、詳細的講解粱年,你就需要掌握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);
}
}

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

文件類型粱快,文件縮略圖呢事哭?鳍咱?谤辜?

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

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

//獲取當前目錄下的所有文件 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];

//數字格式化

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

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

NSInteger maxLength = 128;

uint8_t readBuffer [maxLength];

//是否已經到結尾標識

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

}

異步文件的讀取 涡戳,在網絡方面渔彰,由于網絡的不可靠性可能會造成NSFileManager的文件操作方法的阻塞推正,而以流的方式進行操作則可以實現(xiàn)異步的讀取舔稀。

NSStream是可以異步工作的内贮。可以注冊一個在流中有字節(jié)可讀的時候回調的函數什燕,如果沒有可讀的屎即,就不要阻塞住技俐,回調出去统台。

作者:1115443231
鏈接:http://www.reibang.com/p/357ddad99de8
來源:簡書
著作權歸作者所有贱勃。商業(yè)轉載請聯(lián)系作者獲得授權,非商業(yè)轉載請注明出處仇穗。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末纹坐,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子观谦,更是在濱河造成了極大的恐慌姨丈,老刑警劉巖畴椰,帶你破解...
    沈念sama閱讀 222,807評論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件祖屏,死亡現(xiàn)場離奇詭異援奢,居然都是意外死亡蓖谢,警方通過查閱死者的電腦和手機根吁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,284評論 3 399
  • 文/潘曉璐 我一進店門片林,熙熙樓的掌柜王于貴愁眉苦臉地迎上來端盆,“玉大人,你說我怎么就攤上這事费封』烂睿” “怎么了弓摘?”我有些...
    開封第一講書人閱讀 169,589評論 0 363
  • 文/不壞的土叔 我叫張陵,是天一觀的道長璧针。 經常有香客問我,道長隧膏,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,188評論 1 300
  • 正文 為了忘掉前任湖员,我火速辦了婚禮,結果婚禮上凳寺,老公的妹妹穿的比我還像新娘逆趋。我一直安慰自己,他們只是感情好魄眉,可當我...
    茶點故事閱讀 69,185評論 6 398
  • 文/花漫 我一把揭開白布晃择。 她就那樣靜靜地躺著,像睡著了一般激况。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上浙踢,一...
    開封第一講書人閱讀 52,785評論 1 314
  • 那天蹬挤,我揣著相機與錄音焰扳,去河邊找鬼扫茅。 笑死爆雹,一個胖子當著我的面吹牛慧起,可吹牛的內容都是我干的。 我是一名探鬼主播灿意,決...
    沈念sama閱讀 41,220評論 3 423
  • 文/蒼蘭香墨 我猛地睜開眼荒辕,長吁一口氣:“原來是場噩夢啊……” “哼叠骑!你這毒婦竟也來了掉房?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 40,167評論 0 277
  • 序言:老撾萬榮一對情侶失蹤睬隶,失蹤者是張志新(化名)和其女友劉穎银萍,沒想到半個月后,有當地人在樹林里發(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 46,698評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡呀袱,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,767評論 3 343
  • 正文 我和宋清朗相戀三年乡革,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,912評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡蟹腾,死狀恐怖炉爆,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 36,572評論 5 351
  • 正文 年R本政府宣布碗淌,位于F島的核電站,受9級特大地震影響纳像,放射性物質發(fā)生泄漏岔帽。R本人自食惡果不足惜贾费,卻給世界環(huán)境...
    茶點故事閱讀 42,254評論 3 336
  • 文/蒙蒙 一唱凯、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,746評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽辣苏。三九已至煌张,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間误趴,已是汗流浹背看杭。 一陣腳步聲響...
    開封第一講書人閱讀 33,859評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人轴或。 一個月前我還...
    沈念sama閱讀 49,359評論 3 379
  • 正文 我出身青樓蚕愤,卻偏偏與公主長得像裕坊,于是被迫代替她去往敵國和親声诸。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,922評論 2 361

推薦閱讀更多精彩內容