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)出去诫肠。